Module 8 · Python Data Structures — topic 19 of 22
Updating dictionaries
Add, change and remove dictionary entries: assignment, update() and the | merge operators, setdefault(), counting with get(), and pop(), popitem() and del for removal.
Learning objectives
- Add and change entries
- Merge dictionaries with update() and |
- Remove entries safely and count with get()
Definition
Add, change and remove dictionary entries: assignment, update() and the | merge operators, setdefault(), counting with get(), and pop(), popitem() and del for removal.
Introduction
Dictionaries are mutable: you can add new pairs, change values and remove pairs at any time. Most updates use simple assignment, d[key] = value, which either adds a new key or replaces the value of an existing one.
Why it matters
Inventories change, scores accumulate, settings are overridden by user preferences. Updating dictionaries correctly, especially counting and merging, is a core skill for data processing.
Detailed explanation
d[key] = value adds the key if it is new or replaces its value if it exists.
d[key] += 1 only works if the key already exists. For counting, use d[key] = d.get(key, 0) + 1.
d.update(other) copies all pairs from another dictionary (or iterable of pairs), overwriting existing keys.
d | other returns a new merged dictionary and d |= other updates in place; on clashes the right-hand value wins.
d.setdefault(key, default) returns the value if the key exists, otherwise inserts the default and returns it, handy for grouping into lists.
Remove with del d[key] (KeyError if missing), d.pop(key, default) which returns the value, d.popitem() which removes the last inserted pair, or d.clear().
Don’t add or remove keys while looping over a dictionary; loop over list(d) or build a new dictionary.
Syntax
- Assignment adds or replaces.
- get() makes counting safe.
- pop() with a default never raises KeyError.
Code examples
Adding, changing, removing
{'pen': 35, 'pad': 12}
12 {'pen': 35}
not stockedCounting with get()
{'red': 3, 'blue': 1, 'green': 1}More examples
Merging settings and grouping
{'theme': 'dark', 'font_size': 16, 'autosave': True}
['autosave', 'font_size', 'language', 'theme']
{'A': ['Asha', 'Chen'], 'B': ['Ben']}
{'theme': 'dark', 'font_size': 16}Step-by-step explanation
- defaults | user merges the two; user values win where keys clash.
- update() adds the language key to defaults in place.
- setdefault(section, []) returns the existing list or creates a new one, so names are grouped by section.
- Looping over list(settings) allows deleting keys safely.
Expected output
Running “Merging settings and grouping” prints exactly:
Practical applications
- Applications merge default settings with user preferences.
- Word-frequency tools count words in a dictionary.
- Shopping carts update quantities by product ID.
Best practices
- Use get() or setdefault() for counting and grouping.
- Use | to merge without changing the originals.
- Use pop(key, default) when a key may be missing.
Common mistakes
Incrementing a missing key
Avoid
Prefer
+= reads the old value first, which raises KeyError for a new key.
Deleting while iterating
Avoid
Prefer
Changing a dictionary’s size during iteration raises RuntimeError.
Key takeaways
- d[key] = value adds or replaces.
- update(), | and |= merge; the right side wins on clashes.
- pop, popitem, del and clear remove entries.
Try it yourself
- 1Count how many times each letter appears in a word using a dictionary and get().
- 2Group a list of words by their first letter using setdefault().
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?