Dictionary Exercises
Practice what you've learned about dictionaries with these exercises.
Exercise 1: Merge Two Dictionaries
Write a Python program to merge two dictionaries.
Solution:
# Merging two dictionaries
dict1 = {"name": "Karthick AG", "age": 30}
dict2 = {"city": "Chennai", "email": "karthick@example.com"}
# Method 1: Using update()
dict1.update(dict2)
print("Merged Dictionary:", dict1)
Merged Dictionary: {'name': 'Karthick AG', 'age': 30, 'city': 'Chennai', 'email': 'karthick@example.com'}
Exercise 2: Access Nested Dictionary Items
Access the age of the employee with key 'emp2' from the nested dictionary.
Solution:
# Accessing nested dictionary items
employees = {
"emp1": {"name": "Karthick AG", "age": 30},
"emp2": {"name": "Durai", "age": 28}
}
age_emp2 = employees["emp2"]["age"]
print("Age of emp2:", age_emp2)
Age of emp2: 28
Exercise 3: Iterate Over Dictionaries
Write a Python program to iterate over dictionaries using for loops.
Solution:
# Iterating over dictionaries
person = {"name": "Vijay", "age": 25, "city": "Madurai"}
for key, value in person.items():
print(f"{key} => {value}")
name => Vijay
age => 25
city => Madurai
Explanation: These exercises help reinforce the concepts of dictionary operations by applying them to practical problems.