Fix Python – List of tuples to dictionary [duplicate]

Question

Asked By – Sarah Vessels

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.

Now we will see solution for issue: List of tuples to dictionary [duplicate]


Answer

Just call dict() on the list of tuples directly

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

This question is answered By – Sven Marnach

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0