Python Dictionary Comprehension
In this tutorial, we are going to dive into Dictionary Comprehension. This is a way in which you can create a brand new dictionary in one line of code.
There are other types of comprehension in python. In fact we have covered list comprehension in an earlier article.
If you want to watch a YouTube video based around the content in this article it is embedded below.
Dictionary Comprehension Syntax
Below is the syntax to follow for this lesson. An iterable is anything you can loop through with a for loop.
{key_expression: value_expression for item in iterable if condition}
Example 1
concerts = { 'Trivium': 100, 'Nine Inch Nails': 120, 'Foo Fighters': 90, 'Queens of the Stone Age': 110 }
Let’s break down the code below.Â
key: value + 15 only impacts the db number keeping the artist strings the same.
For (key, value) in concerts.items() allows us to loop over each artist and the db amount.
Concert.items() will give you a list of key-value pairs: [(“Trivium”, 100), (“Nine Inch Nails”, 120), (“Foo Fighters”, 90), (“Queens of the Stone Age”, 110)]
new_concert = {key: value + 15 for (key, value) in concerts.items()} print(new_concert)
{‘Trivium’: 115, ‘Nine Inch Nails’: 135, ‘Foo Fighters’: 105, ‘Queens of the Stone Age’: 125}
Example 2 - Dictionary comprehension with conditional logic
Let’s now look at an example where we want to filter our dictionary. Let’s only have bands that have concerts with over 100 db in our final dictionary.
The if statement is at the very end of the line of code.
filtered_bands = {Band: DB for Band, DB in concerts.items() if DB < 101} print(filtered_bands)
{‘Trivium’: 100, ‘Foo Fighters’: 90}
Example 3
songs = ['March of the Pigs','Copy of a', 'Wish']
We get the length of the title by passing in song to len()
song_length = {Song: len(Song) for Song in songs} print(song_length)
{‘March of the Pigs’: 17, ‘Copy of a’: 9, ‘Wish’: 4}
Example 4 - Create a dictionary from two lists
We will utilize the same songs as above but now map them to specific NIN albums.
songs = ['March of the Pigs','Copy of a', 'Wish']
albums = ['The Downward Spiral', 'Hesitation Marks', 'Broken']
We introduce Zip in this example. Essentially Zip allows us to aggregate elements from iterable into a single iterable of tuples. Want to learn more about it? Check out our Python Zip Tutorial.
nin_dict = {songs: albums for songs, albums in zip(songs, albums)} print(nin_dict)
{‘March of the Pigs’: ‘The Downward Spiral’, ‘Copy of a’: ‘Hesitation Marks’, ‘Wish’: ‘Broken’}
Example 5 - Combine two Dictionaries
While this is not Dictionary Comprehension, it was originally included in the video. Let’s build out two dictionaries by using dictionary unpacking.
Band_List_1 = {'While She Sleeps': 305, 'Wage War': 450}
Band_List_2 = {'Architects': 620, 'Breaking Benjamin': 800, 'Slipknot': 1015}
**unpacks all key-value pairs and {} combines the two dictionaries into a new dictionary called combined_concert_list.Â
combined_concert_list = {**Band_List_1, **Band_List_2} print(combined_concert_list)
{‘While She Sleeps’: 305, ‘Wage War’: 450, ‘Architects’: 620, ‘Breaking Benjamin’: 800, ‘Slipknot’: 1015}
Example 6
Since tuples are an iterable, we can use them in dictionary comprehension. Let’s look at a few famous athletes in Baseball, Hockey, and Cricket.
sports = (('Baseball', 'Babe Ruth'), ('Hockey', 'Wayne Gretzky'), ('Cricket', 'Don Bradman'))
By grabbing the index, we select the part of the tuple. [0] is the sport and [1] is the athlete.
sport_dic = {sport[0]: sport[1] for sport in sports} print(sport_dic)
{‘Baseball’: ‘Babe Ruth’, ‘Hockey’: ‘Wayne Gretzky’, ‘Cricket’: ‘Don Bradman’}
Example 7
Inside dictionary comprehension we can also use range(it’s an iterable) and a function for the expression part of the syntax.
Let’s create a very basic function which squares a number.
def square(x): return x * x
Inside the dictionary comprehension we now have the function square in which we pass in a num from range.
my_dict = {num: square(num) for num in range(1, 11)} print(my_dict)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Example 8
Another usecase of dictionary comprehension is to find the word frequency in a statement of text.Â
Down below is a famous NIN lyric. Let’s take a look at the frequency of every word.
pig_lyrics = "Nothing can stop me now 'cause I don't care anymore \ Nothing can stop me now 'cause I don't care \ Nothing can stop me now 'cause I don't care anymore \ Nothing can stop me now 'cause I just don't care"
We use split to seperate each word on the spacing. Additionaly we use count to add up each time a word is used.
word_freq = {word: pig_lyrics.count(word) for word in set(pig_lyrics.split())} print(word_freq)
{‘Nothing’: 4, ‘now’: 4, ‘anymore’: 2, ‘me’: 4, ‘can’: 4, ‘stop’: 4, ‘I’: 4, “don’t”: 4, ‘just’: 1, “’cause”: 4, ‘care’: 4}
Example 9
Enumerate allows us to map an index to each element in a list when we create the new dictionary.Â
lyric_words = ['Nothing', 'can', 'stop', 'me', 'now', 'cause', 'I', 'dont', 'care']
index = {i:j for (i, j) in enumerate(lyric_words)} print(index)
{0: ‘Nothing’, 1: ‘can’, 2: ‘stop’, 3: ‘me’, 4: ‘now’, 5: ’cause’, 6: ‘I’, 7: ‘dont’, 8: ‘care’}
Example 10
This example reverses what we did above.Â
index_v2 = {i:j for (j, i) in enumerate(lyric_words)} print(index_v2)
{‘Nothing’: 0, ‘can’: 1, ‘stop’: 2, ‘me’: 3, ‘now’: 4, ’cause’: 5, ‘I’: 6, ‘dont’: 7, ‘care’: 8}
Example 11
In this example we take a dictionary and remove keys that we do not want in our final dictionary.
bands_seen_live = {'Beartooth': 5, 'Trivium': 5, 'Shinedown': 4, 'Currents': 4, 'Silent Planet': 4, 'Death Cab For Cutie': 4}
metal_bands = {Band:bands_seen_live[Band] for Band in bands_seen_live.keys() - {'Shinedown', 'Death Cab For Cutie'}} print(metal_bands)
{‘Currents’: 4, ‘Trivium’: 5, ‘Beartooth’: 5, ‘Silent Planet’: 4}
Example 12
This example is the opposite as we only want specific keys in our final dictionary.
rock_bands = {Band:bands_seen_live[Band] for Band in ('Shinedown', 'Death Cab For Cutie')} print(rock_bands)
{‘Shinedown’: 4, ‘Death Cab For Cutie’: 4}
Ryan is a Data Scientist at a fintech company, where he focuses on fraud prevention in underwriting and risk. Before that, he worked as a Data Analyst at a tax software company. He holds a degree in Electrical Engineering from UCF.