List of tuples to dictionary
Solution 1
Just call dict()
on the list of tuples directly
>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}
Solution 2
It seems everyone here assumes the list of tuples have one to one mapping between key and values (e.g. it does not have duplicated keys for the dictionary). As this is the first question coming up searching on this topic, I post an answer for a more general case where we have to deal with duplicates:
mylist = [(a,1),(a,2),(b,3)]
result = {}
for i in mylist:
result.setdefault(i[0],[]).append(i[1])
print(result)
>>> result = {a:[1,2], b:[3]}
Solution 3
The dict
constructor accepts input exactly as you have it (key/value tuples).
>>> l = [('a',1),('b',2)]
>>> d = dict(l)
>>> d
{'a': 1, 'b': 2}
From the documentation:
For example, these all return a dictionary equal to {"one": 1, "two": 2}:
dict(one=1, two=2) dict({'one': 1, 'two': 2}) dict(zip(('one', 'two'), (1, 2))) dict([['two', 2], ['one', 1]])
Solution 4
With dict
comprehension:
h = {k:v for k,v in l}
Sarah Vessels
I'm a software developer at GitHub, working out of Nashville, Tennessee. I love black tea and electropop, puns and hot chicken. When I'm not writing code, I'm playing video games like Skyrim, Diablo 3, and The Sims series. I sometimes blog about video games and tech.
Updated on November 18, 2020Comments
-
Sarah Vessels over 3 years
Here's how I'm currently converting a list of tuples to dictionary in Python:
l = [('a',1),('b',2)] h = {} [h.update({k:v}) for k,v in l] > [None, None] h > {'a': 1, 'b': 2}
Is there a better way? It seems like there should be a one-liner to do this.
-
Sarah Vessels almost 13 yearsDerp, I knew there would be a simple way to do it... Coming from Ruby here, trying to learn the Python way of doing things. Thanks!
-
jfunk about 6 yearsnice because it allows you to do formatting on the key / value before adding it to the dict
-
Sven Marnach about 6 years@chandresh This does work in Python 3, so no update is required.
-
CKM about 6 years@SvenMarnach, Here is my output of the same command you have written above on py 3.5 terminal. Traceback (most recent call last): File "<ipython-input-313-7bb3559567ff>", line 1, in <module> dict(my_list) TypeError: 'Dictionary' object is not callable
-
Sven Marnach about 6 years@chandresh This has nothing to do with Python 3 – it's because you have a variable called
dict
, shadowing the Python built-in of the same name. You should never do that. -
CKM about 6 years@SvenMarnach Oh. Thanks. It worked. Actually, I got some code from the web and tried to run this. Looks like the author had used
dict
as variable name from where I got the error. Thanks again. -
Abhijit Sarkar over 3 yearsOr just use
defaultdict(list)
-
Rim over 3 yearsIf have redundant numbers, it doesn't work properly [('0', '1'), ('0', '3'), ('3', '2')] result : {'0': '3', '3': '2'} instead of {'0':['1', '3'], '3': '2'}
-
Sven Marnach over 3 years@Rim It's not clear at all what the desired outcome is in the presence of duplicate keys. See this answer for one way of achieving what you want.
-
Marcus about 3 yearsNice, also because this works for Python 2. The above answers do not.
-
w123 over 2 years@AbhijitSarkar don't forget to import defaultdict from collections before!