Merging dictionaries
Hey there young Python enthusiast! Today, we’re going to dive into the fascinating world of dictionaries in Python. Imagine you have a magical bookshelf where each book has a unique label. That’s what a dictionary is in Python – it’s like a magical bookshelf where each book (or item) has its own label (or key). We’ll learn how to combine these dictionaries, sort of like organizing books from different bookshelves into one big bookshelf.
What are Dictionaries?
Before we jump into merging them, let’s understand what dictionaries are. In Python, a dictionary is a collection of items, just like a list. But, instead of being indexed by numbers like in a list, dictionaries are indexed by keys, which can be any immutable type, like strings or numbers.
Here’s a quick example:
# Creating a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 1}
# Accessing values using keys
print(my_dict['apple']) # Output: 2
Merging Dictionaries:
Now, let’s say we have two dictionaries and we want to combine them. Python provides us with a handy way to merge dictionaries using the update()
method or the **
operator.
Here’s how we can do it:
# Two dictionaries
dict1 = {'apple': 2, 'banana': 3}
dict2 = {'orange': 1, 'grapes': 4}
# Using update() method
dict1.update(dict2)
print(dict1) # Output: {'apple': 2, 'banana': 3, 'orange': 1, 'grapes': 4}
# Using ** operator
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'apple': 2, 'banana': 3, 'orange': 1, 'grapes': 4}
Practice Questions:
- Question: Merge the following dictionaries:
dict1 = {'a': 1, 'b': 2}
anddict2 = {'b': 3, 'c': 4}
.
Solution:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
- Question: Merge the dictionaries
dict1
anddict2
such that the values of common keys are added together.
Solution:
dict1 = {'a': 5, 'b': 2, 'c': 3}
dict2 = {'b': 3, 'c': 4, 'd': 1}
merged_dict = dict1.copy()
for key, value in dict2.items():
if key in merged_dict:
merged_dict[key] += value
else:
merged_dict[key] = value
print(merged_dict) # Output: {'a': 5, 'b': 5, 'c': 7, 'd': 1}
So, there you have it! Merging dictionaries in Python is like combining different sets of items into one. With the update()
method or the **
operator, you can easily merge dictionaries and play around with your Python magic. Keep practicing, and soon you’ll be a pro at manipulating dictionaries! Happy coding! 🐍✨