- Home
- /
- Python Add/Remove Dictionaries Items
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Add/Remove Dictionaries Items
Add and Remove Items in Dictionaries
Dictionaries in Python aren’t just for storing data — you can also add or remove items at any time. Let’s learn how to do that step by step.
Adding Items to a Dictionary
You can add new data into a dictionary in two simple ways:
1. Assigning a New Key
If the key doesn’t already exist, Python will create it.
profile = {'username': 'ammar42', 'level': 5, 'active': True}
print("Before adding:", profile)
profile['joined_year'] = 2022
print("After adding:", profile)
Output:
Before adding: {'username': 'ammar42', 'level': 5, 'active': True}
After adding: {'username': 'ammar42', 'level': 5, 'active': True, 'joined_year': 2022}
2. Using the update() Method
This method is great for adding or updating values in one go.
profile = {'username': 'ammar42', 'level': 5, 'active': True}
print("Before update:", profile)
profile.update({'level': 6}) # Update existing key
profile.update({'country': 'Pakistan'}) # Add new key
print("After update:", profile)
Output:
Before update: {'username': 'ammar42', 'level': 5, 'active': True}
After update: {'username': 'ammar42', 'level': 6, 'active': True, 'country': 'Pakistan'}
Removing Items from a Dictionary
Python gives you several tools to remove data when it’s no longer needed.
1. clear() — Remove Everything
This wipes out the dictionary, leaving it empty.
student = {'name': 'Alina', 'grade': 'A', 'passed': True}
student.clear()
print(student)
Output:
{}
2. pop() — Remove Specific Item
Give the key, and this method removes that pair.
student = {'name': 'Alina', 'grade': 'A', 'passed': True}
student.pop('passed')
print(student)
Output:
{'name': 'Alina', 'grade': 'A'}
3. popitem() — Remove the Last Pair
It deletes the last item that was added to the dictionary.
student = {'name': 'Alina', 'grade': 'A', 'year': 2023}
student.popitem()
print(student)
Output:
{'name': 'Alina', 'grade': 'A'}
4. del Keyword — Remove by Key or Entirely
Use del if you want to delete a particular key or even the entire dictionary.
student = {'name': 'Alina', 'grade': 'A', 'year': 2023}
del student['grade']
print(student)
Output:
{'name': 'Alina', 'year': 2023}
If you remove the whole dictionary:
student = {'name': 'Alina', 'grade': 'A'}
del student
print(student)
Output:
NameError: name 'student' is not defined
Summary
Add new items by assigning a key or using
.update().Remove specific items with
pop()ordel.Use
clear()to empty the dictionary.Use
popitem()to remove the last item.
With these tools, you can manage your dictionary like a pro!