Adding & Updating Items
-
This lesson explains how to insert new items and update existing values in Python dictionaries.
Adding Items to a Dictionary
We can add a new item by assigning a value to a new key.
Syntax
dictionary_name[key] = value
Adding a New Item
This example adds a new student and marks into a dictionary.
student_marks = {
"Amit": 85,
"Riya": 90
}
student_marks["Rahul"] = 88 # Adding new item
print(student_marks)
2. Updating Existing Items
If the key already exists, assigning a new value will update it.
Syntax
dictionary_name[key] = new_value
Updating an Existing Item
This example updates marks of an existing student.
student_marks = {
"Amit": 85,
"Riya": 90
}
student_marks["Amit"] = 95 # Updating value
print(student_marks)
3. Using update() Method
The update() method adds multiple items or updates existing ones.
Syntax
dictionary_name.update({key:value})
Adding Multiple Items
This example adds new students and updates existing data.
student_marks = {
"Amit": 85,
"Riya": 90
}
student_marks.update({
"Rahul": 88,
"Riya": 92 # Updated value
})
print(student_marks)
Add Item Using Input
User enters key and value, which are added to the dictionary.
data = {}
key = input("Enter key: ")
value = input("Enter value: ")
data[key] = value
print(data)
Why We Remove Items?
In real programs, we often need to:
Delete old records
Remove incorrect data
Clear temporary data
Manage dynamic information
Example: Removing a student who left the course.
Methods to Remove Items
There are 4 main ways to remove data from a dictionary:pop()
popitem()
del keyword
clear()
1. pop() Method
Removes an item using its key and returns the removed value.
Syntax
dictionary.pop(key)
Remove Item Using pop()
Removes a specific key from the dictionary.
student = {"name": "Amit", "age": 20, "marks": 85}
removed_value = student.pop("age")
print("Removed Value:", removed_value)
print("Updated Dictionary:", student)
2.popitem() Method
Removes the last inserted item from the dictionary.
Syntax
dictionary.popitem()
Remove Last Item Using popitem()
Deletes the last key-value pair.
student = {"name": "Amit", "age": 20, "marks": 85}
last_item = student.popitem()
print("Removed Item:", last_item)
print("Updated Dictionary:", student)
3. del Keyword
Deletes a key-value pair using the key name.
del dictionary[key]
Remove Item Using del
Deletes a key from dictionary permanently.
student = {"name": "Amit", "age": 20, "marks": 85}
del student["marks"]
print("Updated Dictionary:", student)
4.clear() Method
Removes all items from the dictionary.
Syntax
dictionary.clear()
Clear Entire Dictionary
Removes all data but dictionary still exists.
student = {"name": "Amit", "age": 20, "marks": 85}
student.clear()
print("Dictionary After Clear:", student)
Comparison Table