convert string to dict using list comprehension in python
Posted
by Pavel
on Stack Overflow
See other posts from Stack Overflow
or by Pavel
Published on 2009-08-07T19:00:32Z
Indexed on
2010/06/12
22:42 UTC
Read the original article
Hit count: 232
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?
© Stack Overflow or respective owner