15
votes

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 dictionary from this?

A: 13, B: 14, C: 29 ...

I know I can split but I can't get the right syntax on how to do it. If I split on -, then how do I join the two parts?

Iterating over this seems to much of a pain.

7
I have a related question: What if my string looks like this: 'A-13-27', B-35-42' and I want a dictionary like this: A:(13,27), B:(35,42)? - Shushiro

7 Answers

26
votes

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())
15
votes
>>> 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}
10
votes

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.

5
votes
>>> 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}
2
votes
dict((p.split(' - ') for p in s.split(',')))
1
votes

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}
0
votes

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(',')))