Add Dictionary Items
Dictionaries in Python are dynamic and mutable, which means you can add new key–value pairs at any time.
Adding items is a very common operation when building real-world data structures.
This topic explains all correct ways to add dictionary items, with examples and best practices.
Add Item Using Assignment
The simplest and most common way.
python
student = {
"name": "Jayesh",
"age": 25
}
student["course"] = "Python"
print(student)
If the key already exists, the value is updated.
python
student["age"] = 26
Add Item Using update()
The
update() method adds one or more items at once.python
student.update({"city": "Pune"})
print(student)
python
student.update({"salary": 50000, "active": True})
print(student)
Add Items from Another Dictionary
python
extra = {"experience": 3, "company": "TechCorp"}
student.update(extra)
print(student)
Add Items Conditionally
python
if "email" not in student:
student["email"] = "jayesh@example.com"
print(student)
Add Items Using Loop
python
keys = ["a", "b", "c"]
values = [1, 2, 3]
d = {}
for k, v in zip(keys, values):
d[k] = v
print(d)
Add Items Using setdefault()
setdefault() adds a key only if it does not exist.python
person = {"name": "Amit"}
person.setdefault("age", 30)
print(person)
If key exists, value is not changed.
python
person.setdefault("age", 40)
print(person)
Add Nested Dictionary Items
python
data = {
"user": {
"name": "Riya"
}
}
data["user"]["age"] = 22
print(data)
Add Items Using Dictionary Comprehension
python
numbers = [1, 2, 3]
squares = {x: x*x for x in numbers}
print(squares)
Common Mistakes
Using Duplicate Keys
python
d = {"a": 1, "a": 2}
print(d)
The last value overwrites previous ones.
Using Mutable Keys
python
# d = {[1, 2]: "value"} # TypeError
Keys must be immutable.
Best Practices
- Use assignment for single item
- Use
update()for multiple items - Use
setdefault()for safe defaults - Check key existence when needed
- Keep keys meaningful and consistent
Summary
- Dictionaries allow adding items dynamically
- Assignment and
update()are most common setdefault()prevents overwriting- Keys must be unique and immutable
- Supports nested and bulk additions