List of tuples to dictionary [duplicate]
Asked Answered
A

5

171

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.

Albuminate answered 29/6, 2011 at 14:35 Comment(0)
K
321

Just call dict() on the list of tuples directly

>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}
Kob answered 29/6, 2011 at 14:36 Comment(7)
Derp, 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!Albuminate
@chandresh This does work in Python 3, so no update is required.Kob
@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 callableDummy
@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.Kob
@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.Dummy
If 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'}Tetchy
@Tetchy 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.Kob
H
32

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]}
Higgins answered 14/4, 2020 at 5:18 Comment(2)
Or just use defaultdict(list)Fluxion
@AbhijitSarkar don't forget to import defaultdict from collections before!Kadiyevka
C
25

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]])
Caliber answered 29/6, 2011 at 14:37 Comment(0)
E
24

With dict comprehension:

h = {k:v for k,v in l}
Enterostomy answered 18/10, 2016 at 10:48 Comment(2)
nice because it allows you to do formatting on the key / value before adding it to the dictRf
Nice, also because this works for Python 2. The above answers do not.Wheen
G
2

Functional decision for @pegah answer:

from itertools import groupby

mylist = [('a', 1), ('b', 3), ('a', 2), ('b', 4)]
#mylist = iter([('a', 1), ('b', 3), ('a', 2), ('b', 4)])

result = { k : [*map(lambda v: v[1], values)]
    for k, values in groupby(sorted(mylist, key=lambda x: x[0]), lambda x: x[0])
    }

print(result)
# {'a': [1, 2], 'b': [3, 4]}
Gur answered 18/11, 2020 at 0:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.