Dictionary Comprehension in Python

Manav Narula Oct 10, 2023
Dictionary Comprehension in Python

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)

Output:

[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)

Output:

{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)

Output:

{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)

Output:

 {1: 'True', 2: 'True', 3: 'True', 4: 'True', 5: 'True'}
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python Dictionary