October 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 NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Add Items to a Dictionary in Python

Use d[key] = value to add or replace one dictionary item in Python. For multiple pairs, use update(); choose setdefault() to preserve an existing value.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Assign a value to a key with square brackets: items["apple"] = 3. Python adds the key if it is new and replaces its value if it already exists. For multiple pairs, use update(); to insert only when a key is missing, use setdefault().

Add or replace one key-value pair

A Python dictionary stores key-value pairs, with each key unique within that dictionary. Start with an empty dictionary using {}, then assign a value by key:

settings = {}
settings["theme"] = "dark"
print(settings)  # {'theme': 'dark'}

If you assign to a key that is already present, Python replaces its old value. The official Python 3.14.8 tutorial explains that the old value associated with that key is forgotten.

settings["theme"] = "light"
print(settings["theme"])  # light

Add multiple items with update()

Use update() to add several key-value pairs to an existing dictionary. It changes the dictionary in place, overwrites existing values for keys in the input, and returns None.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
settings.update({"theme": "dark", "font_size": 16})

Its input can be a mapping, an iterable of pairs, or keyword arguments when the keys are valid Python identifiers:

settings.update([("theme", "dark"), ("font_size", 16)])
settings.update(theme="dark")

Do not assign the result back to the dictionary: settings = settings.update(...) would set settings to None. The Python built-in types reference documents the accepted inputs and overwrite behavior.

Add a key only if it is missing

Use setdefault(key, default) when an existing value should be preserved. If the key is present, the method returns its current value without changing it. If it is absent, it inserts the default and returns that value.

settings.setdefault("language", "en")

Choose setdefault() when retaining an existing value matters; use square-bracket assignment when replacement is intended.

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

Merge dictionaries or update one in place

Python 3.9 and later support dictionary merge operators. The | operator creates a new dictionary; the |= operator updates the dictionary on its left. If both dictionaries contain a key, the value from the right-hand dictionary wins.

defaults = {"theme": "light", "font_size": 14}
user_settings = {"theme": "dark"}

combined = defaults | user_settings
# defaults is unchanged; combined has theme "dark"

defaults |= user_settings
# defaults is updated in place

For code that must also run on Python versions before 3.9, use update() to modify a dictionary or copy it first if you need a merged result without changing the original.

Collect several values under one key

A dictionary key can hold a list when you need to group multiple values under it. defaultdict(list) creates an empty list the first time a missing key is accessed, so you can append without checking whether the key exists.

from collections import defaultdict

groups = defaultdict(list)
for category, item in records:
    groups[category].append(item)

See the official collections documentation for defaultdict behavior and grouping examples.

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

Dictionary keys and missing-key lookups

  • Keys must be hashable. Strings and numbers are common choices; tuples work if all their contents are hashable. Lists cannot be keys because they are mutable.
  • Reading a missing key with d[key] raises KeyError.
  • d.get(key) or d.get(key, fallback) can read a key without raising for a missing key, but get() does not insert anything. Use setdefault() when a missing key should be added.

For more detail on dictionary assignment, key constraints, and lookup behavior, see the Python tutorial’s dictionary section.

Quick Recap

Choose the operation that matches the result you want

Goal Use Effect on existing keys
Add or replace one item d[key] = value Replaces the value if the key already exists
Add several pairs to a dictionary d.update(pairs) Overwrites values for keys in the input
Insert a default only for a missing key d.setdefault(key, default) Preserves an existing value
Create a merged dictionary (Python 3.9+) d1 | d2 Creates a new dictionary; the right side wins for duplicate keys
Update a dictionary with another (Python 3.9+) d1 |= d2 Changes d1; the right side wins for duplicate keys
Group multiple values under keys defaultdict(list) Initializes a list when a missing key is accessed

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.