I have a string in the form of:
s = \'A - 13, B - 14, C - 29, M - 99\'
and so on (the length varies). What is the easiest way to create a d
This should work:
dict(map(lambda l:map(lambda j:j.strip(),l), map(lambda i: i.split('-'), s.split(','))))
If you don't want to strip, just do:
dict(map(lambda i: i.split('-'), s.split(',')))
Those who came here with following problem :
convert string a = '{"a":1,"b":2}'
to dictionary object.
you can simply use a = eval(a)
to get a
as object of dictionary from a string object.
>>> dict((k.strip(),int(v.strip())) for k,v in (p.split('-') for p in s.split(',')))
{'A': 13, 'B': 14, 'M': 99, 'C': 29}
>>> 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}
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:
"<key> - <value>"
parts: s.split(',')
"<key> ", " <value>"
pairs: item.split('-')
(k.strip(), v.strip())
Here's an answer that doesn't use generator expressions and uses replace
rather than strip
.
>>> s = 'A - 13, B - 14, C - 29, M - 99'
>>> d = {}
>>> for pair in s.replace(' ','').split(','):
... k, v = pair.split('-')
... d[k] = int(v)
...
>>> d
{'A': 13, 'C': 29, 'B': 14, 'M': 99}