Skip to content

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.

Beginner 12 min read·Lesson 122 of 306 in Python Programming

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

Python
d[key] = value
d[key] = d.get(key, 0) + 1
d.update(other)
merged = d | other
removed = d.pop(key, None)
del d[key]
  • Assignment adds or replaces.
  • get() makes counting safe.
  • pop() with a default never raises KeyError.

Code examples

Adding, changing, removing

Python
stock = {"pen": 40}
stock["pad"] = 12
stock["pen"] = 35
print(stock)
removed = stock.pop("pad")
print(removed, stock)
print(stock.pop("ink", "not stocked"))
Output
{'pen': 35, 'pad': 12}
12 {'pen': 35}
not stocked

Counting with get()

Python
votes = ["red", "blue", "red", "green", "red"]
counts = {}
for v in votes:
counts[v] = counts.get(v, 0) + 1
print(counts)
Output
{'red': 3, 'blue': 1, 'green': 1}

More examples

Merging settings and grouping

Python
defaults = {"theme": "light", "font_size": 14, "autosave": True}
user = {"theme": "dark", "font_size": 16}
settings = defaults | user
print(settings)
defaults.update({"language": "en"})
print(sorted(defaults))
students = [("Asha", "A"), ("Ben", "B"), ("Chen", "A")]
sections = {}
for name, section in students:
sections.setdefault(section, []).append(name)
print(sections)
for key in list(settings):
if key == "autosave":
del settings[key]
print(settings)
Output
{'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:

TextOutput
{'theme': 'dark', 'font_size': 16, 'autosave': True}
['autosave', 'font_size', 'language', 'theme']
{'A': ['Asha', 'Chen'], 'B': ['Ben']}
{'theme': 'dark', 'font_size': 16}

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

counts[word] += 1

Prefer

counts[word] = counts.get(word, 0) + 1

+= reads the old value first, which raises KeyError for a new key.

Deleting while iterating

Avoid

for k in d:
if bad(k):
del d[k]

Prefer

for k in list(d):
if bad(k):
del d[k]

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

  1. 1
    Count how many times each letter appears in a word using a dictionary and get().
  2. 2
    Group 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?
Practise this topic