7 Handy Use Cases Of Dictionary Comprehensions In Python | by Anupam Chugh | Towards Data Science

Comprehensions in Python are syntactic constructs that are used to build sequences from other sequences. Essentially, comprehensions are a fancy form of writing for loops that are more concise and readable.
All comprehensions can be rewritten using for loops but the vice-versa doesn’t hold true. At large, there are four types of comprehension techniques in Python.
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
Generator Comprehensions
The goal of this piece is to show you the power of dictionary comprehensions and how to leverage it in different ways. Before we explore a few interesting cases, let’s understand the syntax as it can confuse a lot of developers when starting out.
Consider the following code that creates a dictionary from a range of numbers with the value being the square of the key:
square_dict = {num: num*num for num in range(1, 6)}print(square_dict)#Output{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Now let’s analyze the syntax of the dictionary expression using the above code as a reference:
The above syntax represents the minimal form of writing a dictionary comprehension. The output of the dictionary comprehension is highlighted in green. All the key-value pairs are assigned to the constructed dictionary.
The iterable doesn’t have to be a dictionary. It can be any python object on which you can loop over — list, tuple, strings, etc.
Unlike list comprehensions, a dictionary comprehension can iterate over a group of keys and values simultaneously as well. By invoking the items() method on a dictionary, you can convert it into a list of tuples of key-value to loop over.
You can also set a conditional statement after the for loop in dictionary comprehension as shown below:
fruits = ['Apple', 'Orange', 'Papaya', 'Banana', '']fruits_dict = {f:len(f) for f in fruits if len(f) > 0}print(fruits_dict)#Output{'Apple': 5, 'Orange': 6, 'Papaya': 6, 'Banana': 6}
Now that we’ve got a good look at the syntax of dictionary comprehensions, let's move onto its applications.
Often a case comes up where you need to build a dictionary that holds the count of each word in a string. The classic way of doing this using for loops would be:
s = 'I felt happy because I saw the others were happy and because I knew I should feel happy'dict = {}for token in s.split(" "):    dict[token] = dict.get(token, 0) + 1
But we can make it significantly shorter using dictionary comprehensions as shown below:
frequency_dict = {token: s.split().count(token) for token in set(s.split())}#Output{'felt': 1, 'and': 1, 'should': 1, 'others': 1, 'saw': 1, 'were': 1, 'knew': 1, 'happy': 3, 'feel': 1, 'the': 1, 'because': 2, 'I': 4}
With a large dictionary, there might come a point where you need to append a single character to all of them. It could be a simple $ symbol for instance.
In another scenario, you might need to remove a character from a key or value string. Here’s an example of how to create a new dictionary by modifying keys and values using dictionary comprehension:
d = {'My_Article1': '1', 'My_Article2' : '2'}my_dict = { k[3:] : '$' + v for k, v in d.items()}#Output{'Article1': '$1', 'Article2': '$2'}
You probably might be interested in only a part of a dictionary that has a certain set of keys. Here’s an example that filters and creates a new dictionary based on a list of keys:
d = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}keys = [1, 2]my_dict = {key: d[key] for key in keys}#Output{1: 'a', 2: 'b'}
But the above code would throw an error when the list of keys contains an extraneous value not present in the dictionary. So, instead of iterating over keys , we’ll look to find the common keys in d and keys using sets as shown below:
my_dict = {key: d[key] for key in set(keys).intersection(d.keys())}
Here’s a third case, where we’re filtering the dictionary by keys containing a specified string:
d = {'num_1': 'a', '2': 'b', 'num_3': 'c', '4': 'd'}filter_string = 'num'filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}#Output{'num_1': 'a', 'num_3': 'c'}
In cases, where your dictionary has unique keys and values and would like to invert the mapping from k:v to v:k you could do it with a for loop in the following way:
d = {'1': 'a', '2': 'b', '3': 'c', '4': 'd'}my_dict = {}for k,v in d.items():    my_dict[v] = k
By using dictionary comprehension, we can do the same thing in a single line as:
my_dict = {v: k for k, v in d.items()}#Output{'a': '1', 'b': '2', 'c': '3', 'd': '4'}
Next up, we have a tuple list where each element holds the country code and name. We’ll create a dictionary out of it using comprehension technique with the country name being the key, and country-code being the value:
tuples = [("US", '+1'), ("Australia", '+61'), ("India", '+91')]my_dict = {k[0]: k[1] for k in tuples}
Sparse vectors generally contain a lot of zero values. We can consider keeping only non-zero values in a dictionary we can save some space. By using the following dictionary comprehension technique, we can convert a sparse vector to key-value pairs with the key being the index from the sparse vector:
values = [0,0,21,0,0,0,100]my_dict = { values.index(v) : v for v in values if v}#Output{2: 21, 6: 100}
There’s another way of writing the above dictionary comprehension that’s slightly more readable:
my_dict = {n: v for n,v in enumerate(values) if v}
if v indicates to add the key and value to the dictionary only if the sparse vector’s element isn’t False, 0, None, etc.
There are different ways to sort a dictionary. We can do it with keys or values, in ascending or descending orders. Let’s take a look.
Here’s an example to sort by keys in ascending and descending order:
d = {"a": 3, "b": 4, "d": 1, "c": 2}dk_ascending = {k: d[k] for k in sorted(d)}#Output{'a': 3, 'b': 4, 'c': 2, 'd': 1}dk_descending = {k: d[k] for k in sorted(d, reverse=True)}#Output{'d': 1, 'c': 2, 'b': 4, 'a': 3}
The below example shows how to sort by value in ascending and descending order:
d = {"a": 3, "b": 4, "d": 1, "c": 2}dv_ascending = {k: d[k] for k in sorted(d, key=d.get)}#Output{'d': 1, 'c': 2, 'a': 3, 'b': 4}dv_descending = {k: d[k] for k in sorted(d, key=d.get, reverse=True)}#Output{'b': 4, 'a': 3, 'c': 2, 'd': 1}
Let’s say we have an unknown number of dictionaries present in a Python List as shown below:
l = [{'a':1}, {'b':2}, {'c':3, 'd' : 4}]
Now, we’d like to flatten the list into a dictionary such that all the sub-dictionaries are merged into a single dictionary. We can use the following doubly nested dictionary comprehension technique:
my_dict = {k: v for d in l for k, v in d.items()}#Output{'a': 1, 'b': 2, 'c': 3, 'd': 4}
We saw a bunch of different use cases for applying dictionary comprehensions in Python. The idea is to use it efficiently and not overdo it. It’s very easy to misuse it for fairly straightforward manipulations.
That’s it for this one — thanks for reading.