Thursday, February 19, 2009

How to convert two Python lists into a dictionary

To convert two Python lists into a dictionary. First, pair the two list with the zip() function, as key-value pairs. The last step is to use the dict() constructor to build a dictionary directly from the key-value pairs.
>>> x = ['a', 'b', 'c']
>>> y = [1 ,2 ,3]
>>> dict(zip(x,y))
{'a': 1, 'c': 3, 'b': 2}

We can also zip the two lists together, as list of tuples, and use the dict() constructor for the iterator of that list.
>>> x = ['a', 'b', 'c']
>>> y = [1, 2, 3]
>>> dict(iter(list(zip(x, y))))
{'a': 1, 'c': 3, 'b': 2}