convert string to dict using list comprehension

Pavel picture Pavel · Aug 7, 2009 · Viewed 19.3k times · Source

I have came across this problem a few times and can't seem to figure out a simple solution. Say I have a string

string = "a=0 b=1 c=3"

I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:

list = string.split()
dic = {}
for entry in list:
    key, val = entry.split('=')
    dic[key] = int(val)

But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the val can be a string.

dic = dict([entry.split('=') for entry in list])

However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.

dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])

So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?

Answer

S.Lott picture S.Lott · Aug 7, 2009

Do you mean this?

>>> dict( (n,int(v)) for n,v in (a.split('=') for a in string.split() ) )
{'a': 0, 'c': 3, 'b': 1}