Dictionary comprehensions are a quick way to make dictionaries in Python using a clear and short syntax. They work like list comprehensions but create dictionaries. Here are five examples of dictionary comprehensions:
- Creating a dictionary of squares of numbers:
squares = {x: x**2 for x in range(1, 6)}
print(squares)
- Mapping names to their lengths:
names = [‘Alice’, ‘Bob’, ‘Charlie’, ‘David’]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
- Creating a dictionary from two lists:
keys = [‘a’, ‘b’, ‘c’]
values = [1, 2, 3]
combined_dict = {k: v for k, v in zip(keys, values)}
print(combined_dict)
- Converting a dictionary’s keys to uppercase:
my_dict = {‘apple’: 1, ‘banana’: 2, ‘cherry’: 3}
uppercase_keys = {key.upper(): value for key, value in my_dict.items()}
print(uppercase_keys)
- Filtering dictionary items based on conditions:
scores = {‘Alice’: 85, ‘Bob’: 72, ‘Charlie’: 90, ‘David’: 65}
passed_students = {name: score for name, score in scores.items() if score >= 70}
print(passed_students)
In each example, we use a dictionary comprehension to create a dictionary by applying a specific rule or condition to each item in an iterable, like a range, list, or dictionary. This approach makes the code short, easy to understand, and efficient.
Source: hashnode.com