Python - How To Dictionary Comprehension in Python

ID : 193

viewed : 79

Tags : PythonPython Dictionary

vote vote


A list is an ordered collection of multiple elements under a common name. It is simple to create and manage lists in Python. To make it easier, we have the list comprehension method available in Python. This method is a lot more concise, elegant and is usually just a single line of code. It usually involves the use of the for loop within square brackets.

The following code demonstrates the use of this method to create a simple list of integers.

lst = [i for i in range(1,10)] print(lst) 


[1, 2, 3, 4, 5, 6, 7, 8, 9] 

A dictionary, on the other hand, is used to store key-value pairs. There is support in Python 2.7 and up for dictionary comprehension also. It is used similarly to create dictionaries in a single line of code.

For example,

d = {i: i*5 for i in range(1,5)} print(d) 


{1: 5, 2: 10, 3: 15, 4: 20} 

In the above code, we assign integers from 1 to 5 as the keys of the dictionary and assign the product of the key and 5 as its value.

We all know that we can create a list of keys and values of a dictionary. Using the dictionary comprehension method, we can easily create a dictionary using elements of a list. It is shown in the example below.

keys = [1,2,3,4,5] vals = ['Mark','Jack','Jake','Sam','Ash']  d = {i:j for i,j in zip(keys,vals)}  print(d) 


{1: 'Mark', 2: 'Jack', 3: 'Jake', 4: 'Sam', 5: 'Ash'} 

The zip() function in the above example is used to return a zip-type object after combining the two lists.

It is worth noting that there are other ways also to create dictionaries faster. For example, we can use the fromkeys() function. This function allows us to create a dictionary by providing the keys from a list. The downside is that it specifies a same value for all keys.

For example,

keys = [1,2,3,4,5]  d = dict.fromkeys(keys,'True')  print(d) 


 {1: 'True', 2: 'True', 3: 'True', 4: 'True', 5: 'True'} 

  • Related HOW TO?