If I have a string that is the output of matching the regexp [MSP]*, what's the cleanest way to convert it to a dict containing keys M, S, and P where the value of each key is true if the key appears in the string?
e.g.
'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 come up with is:
result = {'M': False, 'S': False, 'P': False}
if (matchstring):
for c in matchstring:
result[c] = True
but this seems slightly clunky, I wondered if there was a better way.
Why not use a frozenset (or set if mutability is needed)?
s = frozenset('PMMM')
# now s == frozenset({'P', 'M'})
then you can use
'P' in s
to check whether the flag P exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With