Computer >> Computer tutorials >  >> Programming >> Python

How to create a dictionary with list comprehension in Python?


The zip() function which is an in-built function, provides a list  of tuples containing elements at same indices from two lists. If two lists are keys and values respectively,  this zip object can be used to constructed dictionary object using another built-in function dict()

>>> L1=['a','b','c','d']
>>> L2=[1,2,3,4]
>>> d1=dict(zip(L1,L2))
>>> d1
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

In Python 3.x a dictionary comprehension syntax is also available to construct dictionary from zip object

>>> L2=[1,2,3,4]
>>> L1=['a','b','c','d']
>>> d={k:v for (k,v) in zip(L1,L2)}
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}