How to Use Dictionary Comprehensions: Learn with 5 Examples

How to Use Dictionary Comprehensions: Learn with 5 Examples

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:

  1. Creating a dictionary of squares of numbers:
squares = {x: x**2 for x in range(1, 6)}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
  1. Mapping names to their lengths:
names = ['Alice', 'Bob', 'Charlie', 'David']
name_lengths = {name: len(name) for name in names}
print(name_lengths)
# Output: {'Alice': 5, 'Bob': 3, 'Charlie': 7, 'David': 5}
  1. 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)
# Output: {'a': 1, 'b': 2, 'c': 3}
  1. 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)
# Output: {'APPLE': 1, 'BANANA': 2, 'CHERRY': 3}
  1. 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)
# Output: {'Alice': 85, 'Bob': 72, 'Charlie': 90}

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.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!