← Back to Blog

Common Dict Mistakes

You've covered dicts from every angle. Here are the mistakes that show up most often — and how to fix them.

1. KeyError — accessing a key that doesn't exist

soldier = {"name": "Raven", "score": 85}
print(soldier["rank"])

Output → KeyError: 'rank'

Square brackets raise an error if the key is missing. Use get() when you're not certain:

print(soldier.get("rank", "unassigned"))

Output → unassigned

Or check with in first:

if "rank" in soldier:
    print(soldier["rank"])

2. Capturing None from a modifying method

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

Output → None

update(), clear(), setdefault() — they all modify the dict in place and return None. If you assign the result, you overwrite your dict with nothing.

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

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

Call the method. Don't assign it.

3. Assignment is not a copy

original = {"name": "Raven", "score": 85}
backup = original
backup["score"] = 99
print(original)

Output → {'name': 'Raven', 'score': 99}

backup = original doesn't create a new dict. Both variables point to the same one. Any change through either variable affects both.

backup = original.copy()
backup["score"] = 99
print(original)     # {'name': 'Raven', 'score': 85}
print(backup)       # {'name': 'Raven', 'score': 99}

Use copy() when you need an independent dict.

4. in checks keys — not values

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

Output → False

in checks keys only. To check if a value exists anywhere in the dict:

print(85 in soldier.values())

Output → True

5. Duplicate keys — last one wins

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

Output → {'name': 'Wolf', 'score': 85}

Keys must be unique. If you use the same key twice, the second value overwrites the first — no error, no warning. It just disappears.

6. Modifying a dict while looping over it

scores = {"Raven": 85, "Wolf": 74, "Ghost": 91}
for name in scores:
    if scores[name] < 80:
        del scores[name]

Output → RuntimeError: dictionary changed size during iteration

Python won't let you change a dict's size while you're looping over it. Build a new dict instead:

scores = {"Raven": 85, "Wolf": 74, "Ghost": 91}
passing = {}
for name, score in scores.items():
    if score >= 80:
        passing[name] = score
print(passing)

Output → {'Raven': 85, 'Ghost': 91}

7. pop() without a default

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

Output → KeyError: 'rank'

Always pass a default when the key might be missing:

soldier.pop("rank", None)       # no error — returns None

8. {} is a dict — not a set

empty = {}
print(type(empty))

Output → <class 'dict'>

{} creates an empty dict — not an empty set. You'll see sets in the next subcapter. For now, just know: if you need an empty set, use set(), not {}.

What you should take away

  • Use get() or check with in before square bracket lookup
  • Don't assign the result of update(), clear(), or setdefault()
  • Use copy() when you need an independent dict
  • in checks keys only — use in d.values() to check values
  • Duplicate keys — last value wins, no error
  • Never modify a dict while looping over it — build a new one instead
  • pop() without a default raises KeyError if the key is missing
  • {} is an empty dict — use set() for an empty set
[ login to bookmark ] // copied! 18 views · 2 min
// resources
Other dict_mistakes.py
← prev Dict Mini Project — Pet Shop next → Dicts — The Full Picture
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.