Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Dictionary Comprehension
In this tutorial, we are going to learn how to use dictionary comprehensions in Python. If you are already familiar with list comprehension, then it won't take much time to learn dictionary comprehensions.
Dictionary comprehension provides a concise way to create dictionaries using a single line of code. We need key-value pairs to create a dictionary. The general syntax of dictionary comprehension is:
{key: value for item in iterable}
Basic Dictionary Comprehension
Let's see how to generate numbers as keys and their squares as values within the range of 10. Our result should look like {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}:
# creating the dictionary
squares = {i: i ** 2 for i in range(10)}
# printing the dictionary
print(squares)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Creating Dictionary from Two Lists
We can create a dictionary from two lists using the zip() function to get parallel values. Let's see how to create a dictionary from two separate lists:
# keys
keys = ['a', 'b', 'c', 'd', 'e']
# values
values = [1, 2, 3, 4, 5]
# creating a dict from the above lists
dictionary = {key: value for (key, value) in zip(keys, values)}
# printing the dictionary
print(dictionary)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Using enumerate() for Index-Value Pairs
We can also generate a dictionary from a single list with index as key using the enumerate() method:
# values
values = ['a', 'b', 'c', 'd', 'e']
# generating a dict using enumerate
dictionary = {key: value for (key, value) in enumerate(values)}
# printing the dict
print(dictionary)
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
Dictionary Comprehension with Conditions
You can also add conditions to filter items during dictionary creation:
# creating dict with even numbers only
even_squares = {i: i ** 2 for i in range(10) if i % 2 == 0}
print(even_squares)
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Conclusion
Dictionary comprehensions provide a clean and efficient way to create dictionaries in Python. They are especially useful when transforming data or combining multiple iterables into key-value pairs.
