The world’s leading publication for data science, AI, and ML professionals.

Dictionary Comprehensions in Python

How to use dictionary comprehensions to create dictionaries in python

Photo by Tianyi Ma on Unsplash
Photo by Tianyi Ma on Unsplash

Creating a Dictionary

Let’s say that we want to create a dictionary in python from another iterable object or sequence, such as a list. For example, we have a list of numbers, and we want to create a dictionary that counts how many times each element occurs in that list. Thus, we can have the keys of the dictionary being the different elements (or numbers) in the list, and their corresponding values equal to the number of times that specific element (or number) shows up in the list.

We can use a for loop to create this dictionary as follows:

num_list = [1,1,7,3,5,3,2,9,5,1,3,2,2,2,2,2,9]
count_dict = {}
for num in num_list:
    count_dict[num] = num_list.count(num)
print(count_dict)
# {1: 3, 7: 1, 3: 3, 5: 2, 2: 6, 9: 2}

Notice how we had to first create an empty dictionary, _countdict. Then as we loop through _numlist using a for loop, we are creating key:value pairs in _countdict. The key will equal the current number we are on while iterating through _numlist, and its corresponding value is equal to the count of that number in _numlist.

count() is a list method that returns the number of times the value we pass in occurs in our list.


Dictionary Comprehensions

Just like we have list comprehensions in python, we also have dictionary comprehensions. As we can recall, list comprehensions allow us to create lists from other sequences in a very concise way.


Here is a full tutorial on list comprehensions:

List Comprehensions in Python


Well, we can use dictionary comprehensions in python to create dictionaries in a very concise way as well.

{ key:value for key, value in iterable or sequence }

For example, we can use a dictionary comprehension to create the above dictionary as follows:

num_list = [1,1,7,3,5,3,2,9,5,1,3,2,2,2,2,2,9]
count_dict = {num:num_list.count(num) for num in num_list}
print(count_dict)
# {1: 3, 7: 1, 3: 3, 5: 2, 2: 6, 9: 2}

And that’s it! First, we use curly brackets to establish that we want to create a dictionary (as opposed to a list where we would use brackets). Then, as we loop over _numlist, we are creating key:value pairs as follows: _num:numlist.count(num), where the key is the number (or num), and its value being the count of that number in _numlist.


Dictionary Comprehensions with Condition

Just like in list comprehensions, we can add a condition to our dictionary comprehensions using an if statement after the for loop.

{ key:value for key, value in iterable or sequence if }

For example, if we only want numbers with an even count in our dictionary, we can use the following code:

num_list = [1,1,7,3,5,3,2,9,5,1,3,2,2,2,2,2,9]
count_dict = {num:num_list.count(num) for num in num_list if num_list.count(num)%2==0}
print(count_dict)
# {5: 2, 2: 6, 9: 2}

As we can see, we added an if statement after the for loop within the dictionary comprehension. If the count of the current number is even, we add the corresponding key:value pair to our dictionary. Otherwise, we don’t add that key:value pair to our dictionary.


Three Concepts to Become a Better Python Programmer


Bonus – Sorting a Dictionary

We can also use the sorted() function to sort our dictionary based on the count as follows:

num_list = [1,1,7,3,5,3,2,9,5,1,3,2,2,2,2,2,9]
count_dict = {num:num_list.count(num) for num in num_list}
sorted_dict = dict(sorted(count_dict.items(), key=lambda x:x[1]))
print(sorted_dict)
# {7: 1, 5: 2, 9: 2, 1: 3, 3: 3, 2: 6}

For a full explanation on the above code, check out this tutorial on sorting objects in python:

The Ultimate Guide to Sorting in Python


If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission.

Join Medium with my referral link – Luay Matalka


Conclusion

In this short tutorial, we first reviewed how to create a dictionary with a for loop using an iterable object (such as a list), where we had to create an empty dictionary first. We then learned how to use a dictionary comprehension to create the same dictionary in a more concise and pythonic manner, where we did not have to first create an empty dictionary. We then saw how to add a condition to our dictionary comprehension using an if statement. Lastly, we sorted our dictionary using the sorted() function based on the count values of the numbers in our list.


Related Articles