10 Creative Examples of Dictionary List Comprehension in Python

10 Creative Examples of Dictionary List Comprehension in Python

Introduction

Dictionary list comprehension is a powerful coding technique in Python that enables developers to create new dictionaries by transforming or filtering existing dictionary data. It is an elegant and efficient way of working with dictionaries and is widely used in modern Python programming.

In this article, we will explore 10 creative examples of dictionary list comprehension in Python that will help you understand the power and versatility of this technique.

Example 1: Transform Dictionary Values

Suppose you have a dictionary containing the average temperature in Celsius for five cities as follows:

“`
temps = {‘New York’: 18, ‘Paris’: 22, ‘London’: 16, ‘Tokyo’: 20, ‘Sydney’: 25}
“`

To convert the temperature values from Celsius to Fahrenheit, you can use dictionary list comprehension as follows:

“`
f_temps = {k: ((v * 9/5) + 32) for k, v in temps.items()}
“`

This code will create a new dictionary `f_temps` with the same keys as `temps`, but with the temperature values converted to Fahrenheit.

Example 2: Filter Dictionary Values

Suppose you have a dictionary containing the scores of students in a class as follows:

“`
scores = {‘John’: 85, ‘Jane’: 92, ‘Mike’: 78, ‘Lisa’: 95, ‘Tom’: 80}
“`

To find the students who scored above 90 marks, you can use dictionary list comprehension as follows:

“`
top_students = {k: v for k, v in scores.items() if v > 90}
“`

This code will create a new dictionary `top_students` containing only the keys and values of students who scored above 90 marks.

Example 3: Merge Two Dictionaries

Suppose you have two dictionaries containing customer orders as follows:

“`
orders1 = {‘Apple’: 3, ‘Banana’: 2, ‘Orange’: 5}
orders2 = {‘Kiwi’: 1, ‘Grapes’: 4, ‘Mango’: 2}
“`

To combine the two dictionaries into one, you can use dictionary list comprehension as follows:

“`
orders = {**orders1, **orders2}
“`

This code will create a new dictionary `orders` containing all the key-value pairs from `orders1` and `orders2`.

Example 4: Remove Duplicates

Suppose you have a list containing duplicate values as follows:

“`
colors = [‘Red’, ‘Green’, ‘Blue’, ‘Red’, ‘Green’, ‘Yellow’, ‘Blue’]
“`

To remove duplicates from the list and create a dictionary with the unique values as keys, you can use dictionary list comprehension as follows:

“`
unique_colors = {color: True for color in colors}
“`

This code will create a new dictionary `unique_colors` containing only the unique values as keys.

Example 5: Find the Length of Dictionary Values

Suppose you have a dictionary containing words as keys and their corresponding lengths as values as follows:

“`
words = {‘Python’: 6, ‘Java’: 4, ‘C++’: 3, ‘Ruby’: 4, ‘Perl’: 4}
“`

To find the lengths of values and create a new dictionary with the lengths as keys and the count of values with that length as values, you can use dictionary list comprehension as follows:

“`
lengths = {v: sum([1 for val in words.values() if val == v]) for v in words.values()}
“`

This code will create a new dictionary `lengths` mapping each unique value length with the count of keys having that length.

Example 6: Create a Nested Dictionary

Suppose you have a list of dictionaries containing the names and prices of products as follows:

“`
products = [{‘name’: ‘Product 1’, ‘price’: 100}, {‘name’: ‘Product 2’, ‘price’: 200}, {‘name’: ‘Product 3’, ‘price’: 300}]
“`

To create a new dictionary with the names as keys and the prices as values, you can use dictionary list comprehension as follows:

“`
product_dict = {p[‘name’]: p[‘price’] for p in products}
“`

This code will create a new dictionary `product_dict` containing the names of the products as keys and their corresponding prices as values.

Example 7: Create an Inverted Dictionary

Suppose you have a dictionary containing the names of fruits as keys and their corresponding colors as values as follows:

“`
fruits = {‘Apple’: ‘Red’, ‘Banana’: ‘Yellow’, ‘Grapes’: ‘Green’, ‘Orange’: ‘Orange’}
“`

To create a new dictionary with the colors as keys and the names of the fruits as values, you can use dictionary list comprehension as follows:

“`
colors_dict = {v: k for k, v in fruits.items()}
“`

This code will create a new dictionary `colors_dict` containing the colors of the fruits as keys and the names of the fruits with that color as values.

Example 8: Filter Nested Dictionary

Suppose you have a dictionary containing the names and details of students as follows:

“`
students = {‘John’: {‘age’: 24, ‘gender’: ‘Male’, ‘marks’: 85}, ‘Jane’: {‘age’: 22, ‘gender’: ‘Female’, ‘marks’: 92}, ‘Mike’: {‘age’: 21, ‘gender’: ‘Male’, ‘marks’: 78}, ‘Lisa’: {‘age’: 23, ‘gender’: ‘Female’, ‘marks’: 95}, ‘Tom’: {‘age’: 25, ‘gender’: ‘Male’, ‘marks’: 80}}
“`

To filter students based on gender and create a new dictionary with the names as keys and the age as values, you can use dictionary list comprehension as follows:

“`
filtered_students = {k: v[‘age’] for k, v in students.items() if v[‘gender’] == ‘Female’}
“`

This code will create a new dictionary `filtered_students` containing only the names and ages of female students.

Example 9: Convert Two Lists to a Dictionary

Suppose you have two separate lists, one containing the names of students and the other containing their scores, as follows:

“`
names = [‘John’, ‘Jane’, ‘Mike’, ‘Lisa’, ‘Tom’]
scores = [85, 92, 78, 95, 80]
“`

To create a new dictionary with the names as keys and the scores as values, you can use dictionary list comprehension with `zip()` function as follows:

“`
student_dict = {k: v for k, v in zip(names, scores)}
“`

This code will create a new dictionary `student_dict` mapping the names of the students with their corresponding scores.

Example 10: Sort a Dictionary by Values

Suppose you have a dictionary containing the names and ages of five people as follows:

“`
people = {‘John’: 24, ‘Jane’: 22, ‘Mike’: 21, ‘Lisa’: 23, ‘Tom’: 25}
“`

To sort the dictionary by age and create a new dictionary with the names as keys and the ages as values, you can use dictionary list comprehension with `sorted()` function as follows:

“`
sorted_people = {k: v for k, v in sorted(people.items(), key=lambda x: x[1])}
“`

This code will create a new dictionary `sorted_people` with the same keys as `people`, but with the entries sorted by ascending age.

Conclusion

Dictionary list comprehension is a powerful technique that can help you transform, filter, and manipulate dictionary data in Python. It is an elegant and efficient way of working with dictionaries and is widely used in modern Python programming. By implementing the 10 creative examples discussed in this article, you can enhance your coding skills and take full advantage of the power and versatility of dictionary list comprehension.

Leave a Reply

Your email address will not be published. Required fields are marked *