163

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.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Sarah Vessels
  • 30,930
  • 33
  • 155
  • 222

5 Answers5

308

Just call dict() on the list of tuples directly

>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    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! – Sarah Vessels Jun 29 '11 at 14:39
  • 7
    @chandresh This _does_ work in Python 3, so no update is required. – Sven Marnach Apr 17 '18 at 13:48
  • @SvenMarnach, Here is my output of the same command you have written above on py 3.5 terminal. Traceback (most recent call last): File "", line 1, in dict(my_list) TypeError: 'Dictionary' object is not callable – CKM Apr 23 '18 at 05:57
  • 4
    @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. – Sven Marnach Apr 23 '18 at 07:23
  • @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. – CKM Apr 23 '18 at 09:27
  • 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'} – Rim Nov 26 '20 at 20:38
  • 1
    @Rim It's not clear at all what the desired outcome is in the presence of duplicate keys. See [this answer](https://stackoverflow.com/a/9840828) for one way of achieving what you want. – Sven Marnach Nov 26 '20 at 20:54
31

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]}
pegah
  • 791
  • 8
  • 15
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]])
FogleBird
  • 74,300
  • 25
  • 125
  • 131
23

With dict comprehension:

h = {k:v for k,v in l}
Kenly
  • 24,317
  • 7
  • 44
  • 60
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]}
vladimir
  • 13,428
  • 2
  • 44
  • 70