How to Add to a Dictionary in Python

What you’ll build or solve

You’ll add new key-value pairs to a Python dictionary and update existing keys without errors.

When this approach works best

This approach works best when you:

  • Want to store and update structured data like user profiles, prices, settings, or counters.
  • Need fast lookups by a key, like mapping an id to a record or a name to a score.
  • Are building up a dictionary gradually, like counting events or collecting results in a loop.

Avoid this approach when:

  • Your data is mostly ordered records with the same fields. A list of dictionaries or a dataclass can be easier to work with.

Prerequisites

  • Python installed
  • You know what a dictionary is

Step-by-step instructions

1) Create a dictionary you can add to

Start with an existing dictionary or an empty one.

user= {"name":"Mina","role":"member"}
settings= {}

What to look for: dictionaries use curly braces {} and store key-value pairs like "name": "Mina".


2) Add one item with bracket assignment

The most common way to add to a dictionary is by assigning a value to a key.

settings= {}
settings["theme"]="dark"
settings["language"]="en"

print(settings)

This also updates an existing key:

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

What to look for: if the key is new, Python adds it. If the key already exists, Python overwrites the old value.


3) Add multiple items with update()

Use update() when you want to add or change several keys at once.

profile= {"name":"Sam"}
profile.update({"city":"Boston","age":34})

print(profile)

update() can also take keyword arguments for simple keys:

profile.update(city="New York",verified=True)
print(profile)

What to look for: keys in update() overwrite existing keys, just like bracket assignment.


4) Add only if missing with setdefault()

Use setdefault() when you want to add a key only if it does not exist.

stats= {"views":10}
stats.setdefault("likes",0)
stats.setdefault("views",0)

print(stats)

This is useful when you’re building lists or counters under a key:

tags_by_post= {}

tags_by_post.setdefault("post_1", []).append("python")
tags_by_post.setdefault("post_1", []).append("dict")

print(tags_by_post)

What to look for: setdefault() returns the value for the key, either existing or newly inserted.


5) Combine dictionaries when you have a whole set of keys

If you have another dictionary and want to combine them, use a merge.

Option A (most common): | merge (Python 3.9+)

base= {"host":"localhost","port":5432}
override= {"port":5433}

merged=base|override
print(merged)

Option B (alternative): unpacking with ** (works in older versions too)

merged= {**base,**override}
print(merged)

What to look for: in merges, keys from the right-hand dictionary win if there’s a conflict.


Examples you can copy

Example 1: Add a single key-value pair

cart= {"items":2}
cart["coupon"]="WELCOME10"
print(cart)

Example 2: Count items in a loop

This uses counts.get(word, 0), which returns 0 if word is not in counts.

counts= {}
words= ["python","java","python","go","python","go"]

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

print(counts)

Example 3: Group values into lists under a key

orders_by_user= {}

orders= [
    {"user":"Mina","order_id":101},
    {"user":"Sam","order_id":102},
    {"user":"Mina","order_id":103},
]

fororderinorders:
user=order["user"]
orders_by_user.setdefault(user, []).append(order["order_id"])

print(orders_by_user)

Example 4: Merge defaults with user overrides

defaults= {"theme":"dark","language":"en","notifications":True}
user_overrides= {"theme":"light","notifications":False}

final_settings=defaults|user_overrides
print(final_settings)

Common mistakes and how to fix them

Mistake 1: Trying to use append() on a dictionary

You might write:

data= {}
data.append(("a",1))

Why it breaks: dictionaries do not have append(). That’s a list method.

Correct approach:

data= {}
data["a"]=1
print(data)

Mistake 2: Overwriting a value when you meant to add to a list

You might write:

tags_by_post= {"post_1": ["python"]}
tags_by_post["post_1"]="dict"

Why it breaks: you replaced the list with a string, so you lose the previous tags.

Correct approach:

tags_by_post= {"post_1": ["python"]}
tags_by_post["post_1"].append("dict")
print(tags_by_post)

If the key may not exist yet:

tags_by_post= {}
tags_by_post.setdefault("post_1", []).append("python")
tags_by_post.setdefault("post_1", []).append("dict")
print(tags_by_post)

Troubleshooting

  • If you see KeyError, use dict.get(key, default) or setdefault() before accessing a missing key.
  • If you see TypeError: unhashable type: 'list', use an immutable key like a string, number, or tuple, not a list.
  • If your updates disappear, check you’re not reassigning a new dictionary later in the code.
  • If merges don’t work with |, your Python may be older than 3.9. Use {**a, **b} instead.
  • If you get confusing results after update(), print the dictionary before and after to confirm which keys were overwritten.

Quick recap

  • Add or update one key with d[key] = value.
  • Add several keys with d.update({...}).
  • Add a key only if missing with d.setdefault(key, default).
  • Combine dictionaries with a | b (Python 3.9+) or {**a, **b}.
  • Use get() or setdefault() to avoid KeyError when keys may be missing.