Filter a dictionary in Python using dictionary comprehension

How can we filter a dictionary on some conditions by not using the for and if statements? There are too many situations we should filter an iterable like a list or dictionary in Python programming. The simplest solution is to use the Python dictionary comprehension.

d = {'apple': 5, 'lemon': 3, 'grape': 7}

d2 = {k: v for k, v in d.items()}
d3 = {k: v * v for k, v in d.items()}

print(d2)  # {'apple': 5, 'lemon': 3, 'grape': 7}
print(d3)  # {'apple': 25, 'lemon': 9, 'grape': 49}

The dictionary comprehension is a kind of expression with brackets and the inner for-in statement. Before the for word, write local variables representing a key and value in the new dictionary. The key and value variables are declared in the for statement iterating the items of the original dictionary.

In the declaration of d3, the new value is defined as v * v and v iterates the values of d. So apple is 25 and lemon is 9 in the new dictionary.

Using this technique, we can easily filter a Python dictionary. Let's make the dictionary with the key is not apple and the value is not 7.

d = {'apple': 5, 'lemon': 3, 'grape': 7}

d2 = {k: v for k, v in d.items() if k != 'apple'}
d3 = {k: v for k, v in d.items() if v != 7}

print(d2)  # {'lemon': 3, 'grape': 7}
print(d3)  # {'apple': 5, 'lemon': 3}

The condition in the dictionary comprehension is after the for-in statement using the local key or value variable. The d2 picked up only the keys on the condition it was not apple, which ended up filtering the key is apple. Similarly, the d3 filters the value is 7.


Powered by Markdown