Using dictionary comprehensions
Welcome, young Python enthusiasts! Today, we’re diving into the fascinating world of Python dictionaries and how to manipulate them using a powerful technique called dictionary comprehensions. Don’t worry if you’re not familiar with all the terms yet. By the end of this journey, you’ll be a pro at using dictionaries in Python!
What are Dictionaries?
Imagine you have a magic bookshelf where each book has a unique label. In Python, we call these labels “keys,” and the books are the “values.” Dictionaries in Python work just like this magical bookshelf. They store data in pairs: a key and its corresponding value.
What is Dictionary Comprehension?
Now, imagine you want to add some new books to your magical bookshelf, but you’re feeling lazy. Instead of manually placing each book, you can use a special trick called “dictionary comprehension.” It’s like using a spell to automatically generate new books and place them on the shelf!
Python Code Examples:
Let’s dive into some Python code to see how this works:
# Example 1: Creating a dictionary using dictionary comprehension
numbers = {x: x**2 for x in range(5)}
print(numbers) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Example 2: Filtering dictionary items with conditions
even_numbers = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_numbers) # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# Example 3: Reversing keys and values in a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
reversed_dict = {value: key for key, value in my_dict.items()}
print(reversed_dict) # Output: {1: 'a', 2: 'b', 3: 'c'}
Practice Questions:
Now, it’s time for some practice! Try to solve these questions:
- Create a dictionary where keys are even numbers from 1 to 10, and values are their squares.
- Filter a given dictionary to remove all items with keys less than 5.
- Given a dictionary of names and ages, create a new dictionary where the keys are the ages and the values are lists of names with that age.
Solutions:
Let’s solve these questions together:
even_squares = {x: x**2 for x in range(2, 11, 2)}
print(even_squares)
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
filtered_dict = {key: value for key, value in original_dict.items() if key >= 'e'}
print(filtered_dict)
names_and_ages = {'Alice': 25, 'Bob': 30, 'Charlie': 25, 'David': 30}
age_groups = {}
for name, age in names_and_ages.items():
if age in age_groups:
age_groups[age].append(name)
else:
age_groups[age] = [name]
print(age_groups)
And there you have it! With these solutions, you’re now a wizard at using dictionary comprehensions in Python. Keep practicing, and soon you’ll be able to solve even more magical problems with Python dictionaries!