Creating a dictionary from a string
To solve your example you can do this:
mydict = dict((k.strip(), v.strip()) for k,v in
(item.split('-') for item in s.split(',')))
It does 3 things:
- split the string into
"<key> - <value>"
parts:s.split(',')
- split each part into
"<key> ", " <value>"
pairs:item.split('-')
- remove the whitespace from each pair:
(k.strip(), v.strip())
>>> s = 'A - 13, B - 14, C - 29, M - 99'
>>> dict(e.split(' - ') for e in s.split(','))
{'A': '13', 'C': '29', 'B': '14', 'M': '99'}
EDIT: The next solution is for when you want the values as integers, which I think is what you want.
>>> dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))
{'A': 13, ' B': 14, ' M': 99, ' C': 29}