Welcome to the Dictionary Comprehension lesson of our Python Tutorial! In this comprehensive guide, we'll explore how to create and manipulate dictionaries using a powerful and concise feature called dictionary comprehension. By the end of this lesson, you'll be able to write more efficient and readable code! 📝
A dictionary in Python is a collection of key-value pairs. Keys are unique, and each key is associated with a value. It's a versatile data structure that allows you to store and retrieve data efficiently.
# Simple dictionary example
my_dict = {
'apple': 1,
'banana': 2,
'orange': 3
}Dictionary comprehension is a concise and readable way to create and manipulate dictionaries. It combines the process of iteration and assignment into a single line of code, making it more efficient and easier to understand.
Let's create a dictionary of fruits and their prices using dictionary comprehension:
# Creating a dictionary using dictionary comprehension
fruit_prices = {fruit: price for fruit, price in [('apple', 1), ('banana', 2), ('orange', 3)]}
print(fruit_prices)Output:
{'apple': 1, 'banana': 2, 'orange': 3}
In this example, we used a tuple list [('apple', 1), ('banana', 2), ('orange', 3)] as the iterable. The syntax {fruit: price for fruit, price in iterable} defines the key-value pair structure.
We can also use dictionary comprehension to manipulate existing dictionaries. Let's filter out fruits with prices greater than 1:
# Creating a dictionary
my_dict = {
'apple': 1,
'banana': 2,
'orange': 3,
'grape': 0.5
}
# Filtering fruits with prices greater than 1
expensive_fruits = {fruit: price for fruit, price in my_dict.items() if price > 1}
print(expensive_fruits)Output:
{'banana': 2, 'orange': 3}
In this example, we used the my_dict.items() method to get the key-value pairs from the dictionary and then filtered them using the condition price > 1.
What is a dictionary in Python?
What is dictionary comprehension in Python?
Happy coding! Let's move on to our next lesson, where we'll learn more advanced techniques using dictionary comprehension. ✅