Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk3 min

How to Extend a Dictionary in Python

Use dict.update() to add or replace entries in place, or Python 3.9+ merge operators to combine dictionaries with clear control over mutation and conflicts.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use my_dict.update(other) to add entries to an existing dictionary. It changes the dictionary in place, returns None, and replaces the old value when an incoming entry has the same key. In Python 3.9 and later, | creates a merged dictionary and |= updates one in place.

Choose the right way to extend a dictionary

Need Use Behavior
Add entries to an existing dictionary d.update(other) Mutates d, returns None, and incoming values replace conflicts.
Merge two dictionaries while keeping both inputs unchanged merged = left | right Creates a new dictionary; values from right win conflicts. Available in Python 3.9 and later.
Update an existing dictionary with operator syntax left |= other Mutates left. Available in Python 3.9 and later.
Add or replace a single entry d[key] = value Sets the value for that one key.

Use update() to add or replace entries

Pass a mapping, an iterable of key-value pairs, or keyword arguments whose names are valid Python identifiers. For each key, the incoming value becomes the value stored in the dictionary.

settings = {"theme": "light", "font_size": 12}
settings.update({"theme": "dark", "show_tips": True})

print(settings)
# {'theme': 'dark', 'font_size': 12, 'show_tips': True}

Here, theme already existed, so its value changed to "dark"; show_tips was added. The original dictionary is modified.

Pass key-value pairs

update() also accepts an iterable of pairs, such as a list of two-item tuples:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
d = {"a": 1}
d.update([("b", 2), ("c", 3)])

print(d)
# {'a': 1, 'b': 2, 'c': 3}

Do not assign the return value

update() changes the dictionary directly and returns None. This common mistake replaces your dictionary variable with None:

d = {"a": 1}
d = d.update({"b": 2})  # d is now None

Call d.update(...) on its own when you want to modify d.

Use dictionary merge operators in Python 3.9 and later

Create a new merged dictionary with |

The | operator combines two dictionaries without changing either input. When a key occurs in both, the right-hand dictionary supplies the value.

base = {"timeout": 10, "retries": 2}
custom = {"timeout": 30}
merged = base | custom

print(merged)
# {'timeout': 30, 'retries': 2}
print(base)
# {'timeout': 10, 'retries': 2}

This operator requires dictionary operands; it does not accept a list of pairs as its right-hand side.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Update in place with |=

Use |= when you want operator syntax but need to modify the dictionary on the left. Like update(), it accepts a mapping or an iterable of key-value pairs.

d = {"a": 1}
d |= [("b", 2)]

print(d)
# {'a': 1, 'b': 2}

Both merge operators were added in Python 3.9. Use update() if your code must run on an earlier Python version.

What happens when keys conflict?

For update(), |=, and |, an incoming value replaces the value for an existing key. With the merge operator, the rightmost value wins. These operations do not preserve both values or append one value to another.

When the input mapping has an order, newly added keys follow that mapping’s order. Existing keys retain their position when their values are replaced.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Appending to a value or merging nested dictionaries

Dictionary extension operates on the top-level keys and values; it does not recursively merge nested dictionaries or append to collections stored as values. Choose and perform the value-level operation you want explicitly.

Append to a list stored under a key

d = {"items": ["pen"]}
d["items"].append("notebook")

Update a nested dictionary explicitly

d = {"options": {"color": "blue", "size": "small"}}
d["options"].update({"size": "large", "enabled": True})

This example updates the nested dictionary itself. It does not make dict.update() perform a recursive merge automatically.

Common mistakes to avoid

  • Do not write d = d.update(other); the method returns None.
  • Do not use | with a list of key-value pairs. Use update() or, in Python 3.9 and later, |=.
  • Do not expect duplicate keys to keep both values or append collection contents; the incoming value replaces the existing one.
  • Do not assume nested dictionaries are merged recursively. Specify the operation for their values explicitly.

References

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.