coding
dictionary
keys

How can I add new keys to a dictionary?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, adding a new key to a dictionary is one of the most basic update operations you can perform. The simplest form is assignment: give the dictionary a key and a value, and Python inserts the pair. The interesting part comes from choosing the right update style when keys may already exist, when values should be created lazily, or when you want to add several keys at once.

Add A Single Key With Assignment

The normal way to add a key is direct assignment.

python
1user = {}
2user["name"] = "Ava"
3user["age"] = 30
4
5print(user)

Output:

python
{'name': 'Ava', 'age': 30}

If the key does not exist, Python creates it. If the key already exists, Python replaces the old value.

Use A Variable As The Key

Keys do not have to be written literally. Dynamic keys are common when you build dictionaries in loops or from user input.

python
1scores = {}
2subject = "math"
3scores[subject] = 95
4
5print(scores)

This is the standard pattern when the key comes from another variable.

Add Several Keys At Once With update()

If you already have another dictionary or a set of new key-value pairs, update() is convenient.

python
1settings = {"theme": "light"}
2settings.update({"language": "en", "timezone": "UTC"})
3
4print(settings)

update() inserts missing keys and overwrites existing ones with the new values.

That makes it useful for merging small configuration dictionaries.

Use setdefault() When You Only Want To Add Missing Keys

Sometimes you want to add a key only if it is absent, without overwriting an existing value. setdefault() is built for that.

python
1profile = {"name": "Ava"}
2profile.setdefault("role", "guest")
3profile.setdefault("name", "Override")
4
5print(profile)

The value of name stays unchanged because setdefault() leaves existing keys alone.

This method is especially useful when you are building grouped structures.

python
1by_category = {}
2by_category.setdefault("books", []).append("Clean Code")
3by_category.setdefault("books", []).append("Refactoring")
4
5print(by_category)

Add Nested Keys Carefully

If the dictionary contains other dictionaries, you can add keys at the nested level after retrieving or creating the inner dictionary.

python
1config = {"database": {}}
2config["database"]["host"] = "localhost"
3config["database"]["port"] = 5432
4
5print(config)

The main thing to watch is that the nested dictionary must exist before you index into it.

If it may not exist, create it first:

python
data = {}
data.setdefault("database", {})["host"] = "localhost"
print(data)

When A New Dictionary Is Better Than Mutation

Sometimes you do not want to mutate the original dictionary. In that case, build a new one.

python
1original = {"a": 1}
2updated = {**original, "b": 2, "c": 3}
3
4print(original)
5print(updated)

This is useful when you want predictable, expression-based code or when the old dictionary should remain unchanged.

Common Pitfalls

The most common mistake is forgetting that assignment overwrites an existing value if the key is already present. If preserving the old value matters, use setdefault() or check first.

Another issue is assuming every nested dictionary already exists. data["outer"]["inner"] = value fails if data["outer"] has not been created yet.

It is also easy to misuse mutable defaults. With setdefault(), remember that the default object is used only when the key is missing, so choose it deliberately.

Finally, keep keys hashable. Lists and other mutable types cannot be dictionary keys in Python.

Summary

  • Add a new dictionary key in Python with dict[key] = value.
  • Assignment creates missing keys and overwrites existing ones.
  • Use update() to add or merge multiple key-value pairs.
  • Use setdefault() when a key should be added only if it does not already exist.
  • Make sure nested dictionaries exist before adding inner keys.

Course illustration
Course illustration

All Rights Reserved.