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?
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.
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.
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.
The split() method is the recommended and most common method used to convert string to list in Python.
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}
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With