Python: Dictionary Comprehension
Dictionary comprehension is a way of transforming ones dictionary key and values to another! it can be a powerful tool which makes your…
Dictionary comprehension is a way of transforming ones dictionary key and values to another! it can be a powerful tool which makes your coder shorter and more readable! lets see how it works!
Learning the values(), keys() and items() methods
Lets create a simple dictionary at first! and explore some methods which are crucial to handle comprehensions
my_dict = {}
my_dict['a'] = 1
my_dict['b'] = 2
my_dict['c'] = 3
my_dict['d'] = 4Printing this will print both key and values
print(my_dict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}To print only values we can use the .values() method of the dictionary
print(my_dict.values())
dict_values([1, 2, 3, 4])Keep in mind that .value() returns an iterable list! we will discuss about this later!
To print only keys we can use the .keys() method of the dictionary, which also returns an iterable list
print(my_dict.keys())
dict_keys(['a', 'b', 'c', 'd'])We can get all key and values in a list of tuples using the .items() method
print(my_dict.items())
dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])Creating dictionary comprehensions
The basic template you need to know to create dictionary comprehensions is this
new_dict = {k:v for (k,v) in dictionary.items()}- The for statement iterates the pairs of the dictionary items and saves key and value of each per to k and v respectively
- k:v are are stored as key and values to new_dict dictionary
Might seem like just copying one dictionary to another and yets is that exactly! but the magic starts here!
new_dict = {k:v*v for (k,v) in my_dict.items()}
print(new_dict)
{'a': 1, 'b': 4, 'c': 9, 'd': 16}This way we are able to multiply each value to itself and store the result to the new dictionary! isn't that awesome? if we want to do the same with simple python we would end to something like this which is bigger and less clear that dictionary comprehension
new_dict = {}
for (k,v) in my_dict.items():
new_dict[k] = v * vThe usability of dictionary comprehensions become clearer when we need to add if statements inside the loop, assume that we want to create dictionaries where values are even numbers, it would be something like this!
new_dict = {}
for (k,v) in my_dict.items():
if v%2 == 0:
new_dict[k] = v * vWe can shorten this to one line with this dictionary comprehension, you can plase if statements to the right of the expressions in order to filter keys, values or both!
new_dict = {k:v*v for (k,v) in my_dict.items() if v%2 == 0}
print(new_dict)
{'b': 4, 'd': 16}Conclussion
Dictionary comprehension is a powerful technique which easy to learn and will make your code shorted and more readable! I hope you enjoyed this article as much I enjoyed writing the article!
In Plain English
Thank you for being a part of our community! Before you go:
- Be sure to clap and follow the writer! 👏
- You can find even more content at PlainEnglish.io 🚀
- Sign up for our free weekly newsletter. 🗞️
- Follow us on Twitter(X), LinkedIn, YouTube, and Discord.