Dictionaries in Python can be created in multiple ways. In previous articles, we learned about curly braces {}, dict constructor, copy() method to create dictionary objects. Comprehension is also one of the way to create dictionaries in Python.
Dictionary Comprehension
Python dictionary comprehension is a concise and powerful way to create dictionaries.
- Comprehension allows to construct new dictionary key-values pairs by iterating over each item of an iterable (like list, tuple or another dictionary) and applying the expression on those items.
- Comprehension can also be used to transform, filter or map the data during dictionary creation.
- Comprehension in Dictionary follows a syntax similar to list comprehension
- Syntax of comprehension in dictionary:
dictionary = {key_expression: value_expression for item in iterable if condition == True}
key_expression– This defines the key for each item in the new dictionary. This is generally the items value iterated over the iterable.value_expression– This defines the value associated with each key. This expression can be a transformed based on the iterated item value.iterable–iterablecan be any collection datatype that can be iterated over its elements. This can be a list, tuple, another dictionary etc.item in iterable– This is the item in the current iteration in the iterable.if condition– This is the condition based on which we can filter the iterated items.dictionary– This is the resulted dictionary with key-value pairs created from the comprehension
Comprehension will use loops on the given iterable. Lets first understand loop with dictionary.
for loop and in operator with dictionary
for element in dictionary:
foris the loop to iterator over the elements in dictionaryinoperator is used to get the elements which are present in the dictionary. This is also used to check if given element is present in the iterable (dictionary) or not.
# dictionary iteration
print("dictionary iteration")
courses = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"}
for x in courses: # iterate over elements in courses
print("key - ", x, "value - ", courses[x])
# dictionary membership test
print("dictionary membership test")
courses = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"}
print("c1" in courses) # check c1 present in courses
print("c5" in courses)
print("c2" not in courses) # check c2 not present in courses
- We have defined a dictionary referenced by
courses. We are usingfor x in coursesto iterate over the elements ofcourses. With each iteration,xwill take next key in thecourses. - Again we defined dictionary
courses. We are usinginandnot inoperator to check if the given key is present in dictionary or not."c1" in courseswill check ifc1key is present incourses. If it is present thenTruewill be returned elseFalsewill be returned.
Program Output
dictionary iteration
key - c1 value - Python
key - c2 value - AWS
key - c3 value - Azure
key - c4 value - Java
dictionary membership test
True # c1 present in courses
False # c5 not present in courses
False # c2 present in courses, but was checked for not in
Using for loop all key-value pairs of the dictionary are printed in the output. Using in operator we are able to check if key is present in dictionary or not.
Dictionary Comprehension with for loop
# dictionary comprehension square number
print("dictionary comprehension square number")
square_dict = {x: x**2 for x in [12, 15, 17, 8, 9, 3, 6]} # comprehension create key-value pair
print(square_dict)
print("\n---------------------------------------------------\n")
# dictionary comprehension with string
print("dictionary comprehension with string")
shbytes_dict = {x: x*3 for x in "shbytes"} # comprehension create key-value pair
print(shbytes_dict)
square_dict = {x: x**2 for x in [12, 15, 17, 8, 9, 3, 6]}=> This is creating dictionarysquare_dictwith key-value pair, where keyxis element from the list and value is calculated based on the expressionx**2.shbytes_dict = {x: x*3 for x in "shbytes"}=> This is creating dictionaryshbytes_dictwith key-value pair, where keyxis character from the string and value is calculated based on the expressionx*3.
Program Output
dictionary comprehension square number
{12: 144, 15: 225, 17: 289, 8: 64, 9: 81, 3: 9, 6: 36}
---------------------------------------------------
dictionary comprehension with string
{'s': 'sss', 'h': 'hhh', 'b': 'bbb', 'y': 'yyy', 't': 'ttt', 'e': 'eee'}
- Returned key-value pair, with value as square of the key
- Returned key-value pair, with value as 3 times of key
Dictionary Comprehension with if condition
# dictionary comprehension with conditions
print("dictionary comprehension with conditions")
multiply_even_dict = {x: x*2 for x in [12, 15, 17, 8, 9, 3, 6] if x % 2 == 0} # if condition for even numbers
print(multiply_even_dict)
We are using comprehension {x: x*2 for x in [12, 15, 17, 8, 9, 3, 6] if x % 2 == 0} => if condition will be True only for even numbers. It will create key-value pair only for even numbers and value is calculated based on the expression.
Program Output
dictionary comprehension with conditions
{12: 24, 8: 16, 6: 12} # only even numbers, value double of key
Only even number keys are allowed and value is double of the key.
Dictionary Comprehension with zip() method
# dictionary comprehension - with keys and values
print("dictionary comprehension - with keys and values")
course_keys = ["c1", "c2", "c3", "c4"]
course_values = ["Python", "AWS", "Azure", "ML"]
course_dict = {k: v for (k, v) in zip(course_keys, course_values)}
print(course_dict)
We are using comprehension {k: v for (k, v) in zip(course_keys, course_values)} => zip() method uses two lists course_keys for keys and course_values for values. length of both the lists should be same. On every iteration, next element from both lists will be taken and key-value pair will be added into the dictionary.
Program Output
dictionary comprehension - with keys and values
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'ML'}
Dictionary key-value pairs are created. Corresponding key and value taken from course_keys and course_values list.
Nested Dictionary Comprehension
# nested dictionary comprehension
print("nested dictionary comprehension")
nested_dict = {x: {y: y**2 for y in range(1, 4)} for x in "nest"} # nested dictionary comprehension
print(nested_dict)
From the comprehension {x: {y: y**2 for y in range(1, 4)} for x in "nest"} we are creating nested dictionary. Let’s divide this in two parts:
{y: y**2 for y in range(1, 4)}=> This dictionary is value for outer key. This is generating key-value pair iterating overrangefunction, wherevaluewill be square ofkey.{x: sub_dictionary for x in "nest"}=> This dictionary key is character from string and value is generatedsub_dictionary.
Program Output
nested dictionary comprehension
{'n': {1: 1, 2: 4, 3: 9}, 'e': {1: 1, 2: 4, 3: 9}, 's': {1: 1, 2: 4, 3: 9}, 't': {1: 1, 2: 4, 3: 9}}
Nested dictionary is generated as an output.
Summary
In this article, we learn about loop and comprehension to create dictionary objects. We explored following scenarios:
Code – Github Repository
All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.