← Back to Blog

How to Modify a Dict

The problem...

You have a dict. But data changes.

A soldier gets promoted. A score gets updated. An entry needs to be removed.

Dicts in Python aren't frozen — you can change them after you create them.

The idea!

You already saw that assigning to a key creates or updates it.

Python also gives you dedicated methods for merging, removing, and safely inserting.

Same principle as lists: these methods modify the dict directly.

Adding and updating keys

Assign directly to add a new key or update an existing one:

soldier = {"name": "Raven", "score": 85}
soldier["rank"] = "Sergeant"    # new key
soldier["score"] = 91           # update existing
print(soldier)

Output → {'name': 'Raven', 'score': 91, 'rank': 'Sergeant'}

No error if the key exists. No error if it doesn't. Python handles both the same way.

update() — merge another dict in

update() adds all key-value pairs from another dict into your dict:

soldier = {"name": "Raven", "score": 85}
new_data = {"rank": "Sergeant", "active": True}
soldier.update(new_data)
print(soldier)

Output → {'name': 'Raven', 'score': 85, 'rank': 'Sergeant', 'active': True}

If a key already exists, update() overwrites it:

soldier.update({"score": 99})
print(soldier["score"])

Output → 99

You can also pass keyword arguments directly:

soldier.update(score=75, active=False)

setdefault() — add only if missing

setdefault() adds a key with a value — but only if the key doesn't already exist:

soldier = {"name": "Raven", "score": 85}
soldier.setdefault("rank", "unassigned")
soldier.setdefault("score", 0)          # already exists — not changed
print(soldier)

Output → {'name': 'Raven', 'score': 85, 'rank': 'unassigned'}

Useful when you want to guarantee a key exists without overwriting what's already there.

Removing keys

pop() removes a key and returns its value:

soldier = {"name": "Raven", "score": 85, "rank": "Sergeant"}
removed = soldier.pop("rank")
print(removed)
print(soldier)

Output:

Sergeant
{'name': 'Raven', 'score': 85}

If the key doesn't exist, pop() raises a KeyError. Pass a default to avoid it:

soldier.pop("gear", None)       # no error if missing

popitem() removes and returns the last inserted key-value pair as a tuple:

soldier = {"name": "Raven", "score": 85, "rank": "Sergeant"}
last = soldier.popitem()
print(last)
print(soldier)

Output:

('rank', 'Sergeant')
{'name': 'Raven', 'score': 85}

clear() removes everything:

soldier = {"name": "Raven", "score": 85}
soldier.clear()
print(soldier)

Output → {}

The dict still exists. It's just empty.

What's really happening

All of these modify the dict in place. No new dict is created.

pop() returns the value it removed — everything else returns None.

Don't assign the result of update(), clear(), or setdefault() — you'll overwrite your dict with None.

Heads up!

  • update() overwrites existing keys — no warning
  • setdefault() never overwrites — safe to call even if the key exists
  • pop() raises KeyError if the key is missing — pass a default to avoid it
  • popitem() raises KeyError on an empty dict
  • Assigning the result of update() or clear() gives you None

The mindset shift

Stop thinking: "I need to rebuild the dict every time something changes."

Start thinking: "I modify the dict directly — add, update, or remove exactly what I need."

What you should understand now

  • Assign to a key to add or update it
  • update() merges another dict in — overwrites on conflict
  • setdefault() adds a key only if it doesn't already exist
  • pop() removes a key and returns its value
  • popitem() removes and returns the last inserted pair
  • clear() empties the dict without deleting it
[ login to bookmark ] // copied! 18 views · 2 min
// resources
Code Example dict_modifying.py
← prev How to Ask a Dict for What You Need next → Getting Information From a Dict
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.