views:

41

answers:

2

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.

+6  A: 

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.

KennyTM
interesting... thanks!
Jason S
+3  A: 

In newer versions of Python you can use a dict comprehension:

s = 'MMSMSS'
d = { c: c in s for c in 'MSP' }

In 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 strings because if all three characters occur at the beginning of the string the search can stop early. It won't require searching the entire string.

Mark Byers
`d = dict((c, s in c) for c in 'MSP')`, works in Python 2.6.
KennyTM