List of tuples to dictionary

Sarah Vessels picture Sarah Vessels · Jun 29, 2011 · Viewed 98.7k times · Source

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.

Answer

Sven Marnach picture Sven Marnach · Jun 29, 2011

Just call dict() on the list of tuples directly

>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}