Python: converting string to flags
If I have a string that is the result of a regexp mapping [MSP]*
, then what is the cleanest way to convert it to a dict containing the keys M, S and P, where the value of each key is true if the key appears in the string?
eg.
'MSP' => {'M': True, 'S': True, 'P': True}
'PMMM' => {'M': True, 'S': False, 'P': True}
'' => {'M': False, 'S': False, 'P': False}
'MOO' won't occur...
if it was the input to matching the regexp, 'M' would be the output
The best I can think of is this:
result = {'M': False, 'S': False, 'P': False}
if (matchstring):
for c in matchstring:
result[c] = True
but this seems a little awkward, I was wondering if there is a better way.
+2
a source to share
2 answers
In newer Python versions, you can use dict comprehension:
s = 'MMSMSS'
d = { c: c in s for c in 'MSP' }
On older versions, you can use this as KennyTM points out:
d = dict((c, c in s) for c in 'MSP')
This will give good performance for long lines, because if all three characters occur at the beginning of the line, the search may stop earlier. This does not require searching the entire string.
+3
a source to share