Adding Items
Lesson 6 of 14 in Coddy's Dictionary in Python course.
To add an item to a dictionary use a new key and assign a value to it,
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
my_dict["country"] = "USA" # Add a new key-value pairThe same can be done using update method as we seen last lesson,
my_dict.update({"country": "USA"})Challenge
EasyYou're given a dictionary representing a list of courses and their enrollment numbers. Your task is to modify the dictionary by updating the enrollment numbers of existing courses and adding new courses. Perform the following updates:
- Update the enrollment for the "Math" course to 35.
- Add a new course, "Art," with an enrollment of 15.
- Update the enrollment for the "Science" course to 22.
- Add a new course, "Music," with an enrollment of 18.
Try it yourself
# The course dictionary
courses = {
"Math": 30,
"History": 25,
"Science": 20,
"English": 28
}
# Your code here:
# Don't change below this line
print("Updated Courses:", courses)