Python

Python Dictionary Comprehension with Examples – Data Analysis

Python Dictionary Comprehension with Examples – Data Analysis

In this tutorial, we will cover how dictionary comprehension works in Python. It includes various examples which would help you to learn the concept of dictionary comprehension and how it is used in real-world scenarios.

What is Dictionary Comprehension?

Like list comprehension, dictionary comprehension lets us to run for loop with a single line of code. It makes coding more readable and short.

The difference between list and dictionary comprehension is that list comprehension creates list, whereas dictionary comprehension creates dictionary. Also list is defined with square bracket [ ] whereas dictionary is created with curly braces { }.

Syntax of Dictionary Comprehension

{key:value for item in iterable}

Iterable is any python object (i.e. dictionary, list, tuple or string). Item refers to each element in the iterable you can loop over.

Example 1 : Let’s say you want to create a dictionary where each number is the key and the value is the square of that number.

See the table below showing comparison of dictionary comprehension with For Loop.

Dictionary Comprehension

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

# Output
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

For Loop

d = {}
for i in range(5):
    d[i]=i**2
print(d)

# Output
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

range(5) returns 0 through 4 as indexing in python starts from 0 and excluding end point.

d.keys() # returns [0, 1, 2, 3, 4]
d.values() # returns [0, 1, 4, 9, 16]

Example 2 : Let’s say you have a list of words and you want to create a dictionary where each word is the key and the value is the length of that word.

words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
word_lengths = {i:len(i) for i in words}
print(word_lengths)

# Output
# {'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4, 'elderberry': 10}

Creating a new dictionary based on existing dictionary

The following code creates a new dictionary ‘new_dic’ where each value in the original dictionary ‘dic’ is multiplied by 2.

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
new_dic = {i:j*2 for i,j in dic.items()}
print(new_dic)

# Output
# {'a': 2, 'b': 4, 'c': 6, 'd': 8}

dic.items() returns the whole structure of dictionary which comprises of both keys and values. Here we are looping over each key-value pair (i, j).

How to Filter Dictionary

The following code only includes key-value pairs where the value is greater than 2 and then each value is multiplied by 2.

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
{i:j*2 for i,j in dic.items() if j>2}

# Output
# {'c': 6, 'd': 8}

IF-ELSE Condition in Dictionary Comprehension

This example shows how to identify odd or even numbers in values in dictionary.

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
{i:('even' if j%2==0 else 'odd') for i,j in dic.items()}

# Output
# {'a': 'odd', 'b': 'even', 'c': 'odd', 'd': 'even'}

Removing Selected Items from Dictionary

Suppose you have a dictionary containing cities name along with some values and you want to delete specific multiple items (let’s say Delhi and London) from dictionary. In this example, i refers to keys of dictionary and d[i] evaluates to d[key]. For e.g. d[‘Mumbai] returns 221.

d = {'Delhi': 121, 'Mumbai': 221, 'New York': 302, 'London': 250}
{i:d[i] for i in d.keys() - {'Delhi','London'}}

# Output
# {'New York': 302, 'Mumbai': 221}

Using Enumerate Function in Dictionary Comprehension

Enumerate function runs on list, tuple or string and returns element and its index.

list(enumerate(['a', 'b', 'c']))

# Output
# [(0, 'a'), (1, 'b'), (2, 'c')]

With the use of this function, we can create a dictionary with elements of the list as keys and the index as values.

mylist = ['a', 'b', 'c']
{j:i for i,j in enumerate(mylist)}

# Output
# {'a': 0, 'b': 1, 'c': 2}
Suggested Articles

Leave a Reply

Your email address will not be published. Required fields are marked *