/  Technology   /  Python |Creating a dictionary with List Comprehension
Python |Creating a dictionary with List Comprehension

Python |Creating a dictionary with List Comprehension

Python offers an in-built function called zip()function which provides a list  of tuples containing elements at same indices from two lists.

For example if two lists are keys and values respectively the zip object helps to construct dictionary object with the use of another built-in function dict().

 

Example:

 

A1=['a','b','c','d']
A2=[1,2,3,4]
d1=dict(zip(A1,A2))
d1

 

Output:

 

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

 

Python 3.x also provides a dictionary comprehension syntax to construct dictionary from zip object

 

Example:

 

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

 

Output:

 

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

 

Leave a comment