Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to dict using list comprehension

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?

like image 720
Pavel Avatar asked Aug 07 '09 19:08

Pavel


People also ask

Can I use list comprehension with dictionary?

Using dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary.

How do I turn a list into a dictionary?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.

How do I convert a list to a dictionary in Python w3schools?

The zip() function is an in-built function that takes iterators (can be zero or more), aggregates and combines them, and returns them as an iterator of tuples and the dict() function creates a new dictionary.

How do you convert a string to a list in Python?

The split() method is the recommended and most common method used to convert string to list in Python.


2 Answers

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}
like image 79
S.Lott Avatar answered Oct 10 '22 00:10

S.Lott


How about a one-liner without list comprehension?

 foo="a=0 b=1 c=3"
 ans=eval( 'dict(%s)'%foo.replace(' ',',')) )
 print ans
{'a': 0, 'c': 3, 'b': 1}
like image 23
Vicki Laidler Avatar answered Oct 10 '22 00:10

Vicki Laidler