
Syntax: Dict Editing
Setting and removing dictionary values.
In Python, you can modify dictionaries by adding new key-value pairs, updating existing pairs, or removing pairs altogether.
Adding and Updating Dictionary Values
You can add a new key-value pair or update an existing pair by assigning a value to a key.
user = {
"name": "Bob",
"email": "[email protected]",
"age": 35
}
user["age"] = 36 # updating
user["address"] = "123 Main St" # adding
print(user)
> {"name": "Bob", "email": "[email protected]", "age": 36, "address": "123 Main St"}Removing Dictionary Values
You can remove a key-value pair from a dictionary with the del keyword.
user = {
"name": "Bob",
"email": "[email protected]",
"age": 35,
"address": "123 Main St"
}
del user["address"]
print(user)
> {"name": "Bob", "email": "[email protected]", "age": 35}Practice: Editing a Dictionary
-
Create a dictionary
studentwith keys"name","id", and"course"and assign appropriate values to each key. -
Add a new key-value pair
"age":21to the dictionary. -
Update the value of the key
"course"to"Advanced Data Science". -
Remove the key-value pair with the key
"id". -
Print the updated dictionary.
HINT*: Click here for a hint
> {"name": "Alice", "course": "Advanced Data Science", "age": 21}SOLUTION*: Click here for an example solution
student = {
"name": "Alice",
"id": 123,
"course": "Data Science"
}
student["age"] = 21
student["course"] = "Advanced Data Science"
del student["id"]
print(student)
Practice: Editing a Complex Dictionary
Let's consider a dictionary courses representing a catalog of courses and their corresponding students. Each key in the dictionary is a course name and the value is a list of student IDs.
-
Create the
coursesdictionary with at least three courses and at least two students in each course. -
Add a new student to the
"Data Science"course with theappend()method. -
Remove a student from the
"Web Development"course with theremove()method. -
Print the updated
coursesdictionary.
HINT*: Click here for a hint
> {"Data Science": [111, 112, 118], "Web Development": [114, 115], "Design": [116, 117]}SOLUTION*: Click here for an example solution
courses = {
"Data Science": [111, 112],
"Web Development": [113, 114, 115],
"Design": [116, 117]
}
courses["Data Science"].append(118)
courses["Web Development"].remove(113)
print(courses)
Well done! Being able to edit dictionaries is a crucial part of working with data in Python.