Alex Rivera | Logout

Creating a dictionary from a string

Asked 2011-01-07T16:49:11.653
19

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.

Edit
Report

1 Answer

1

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}
answered 2011-01-07T17:19:32.037

Your Answer