Dictionary Comprehension
Dictionary comprehension is a concise way to create dictionaries in Python. It allows us to create dictionaries by defining the key-value pairs using a compact and expressive syntax.
In this tutorial, we will explore dictionary comprehension in Python, we'll also explain its syntax and provide examples for better understanding.
Basic Syntax of Dictionary Comprehension
The basic syntax for dictionary comprehension consists of curly braces {} containing a key-value pair followed by a for loop.
{key: value for variable in iterable}
-
key: The key to be used in the new dictionary.
-
value: The corresponding value for the key.
-
variable: It takes values from the iterable.
-
iterable: A collection that provides values for the variable.
Creating a Simple Dictionary
Example 1:
squares = {x: x*x for x in range(1, 6)}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
In this example, we create a dictionary that contains the squares of numbers from 1 to 5.
Example 2:
Fruits = ["Apple", "Mango", "Banana", "Orange", "Kiwi"]
my_dict = {Fruit: len(Fruit) for Fruit in Fruits}
print(my_dict)
Output:
{'Apple': 5, 'Mango': 5, 'Banana': 6, 'Orange': 6, 'Kiwi': 4}
Here, we create a dictionary that stores the name of the fruit as a key and the length of the fruit's name as a value.
Conditional Expressions in Dictionary Comprehension
Example 1:
my_dict = {x: x*x for x in range(1,11) if x%2==0 }
print(my_dict)
Output:
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
In above example, we create a dictionary that contains the squares of even numbers from 1 to 10.
Example 2:
names = ["Naman", "Hardik", "Rituraj", "Shivam", "Jogindar"]
max_length = 5
long_names = {name: len(name) for name in names if len(name) <= max_length}
print(long_names)
Output:
{'Naman': 5}