Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dictionary from a string

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.

like image 788
user225312 Avatar asked Jan 07 '11 16:01

user225312


1 Answers

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())
like image 168
Jochen Ritzel Avatar answered Sep 30 '22 13:09

Jochen Ritzel