W3docs

Add Items to a Python Dictionary

Learn four ways to add items to a Python dictionary: square bracket notation, update(), setdefault(), and the Python 3.9+ merge operator, with clear examples.

Python dictionaries are mutable, ordered (since Python 3.7) collections of key-value pairs. Because they are mutable, you can add new entries at any time after creation. This chapter covers every standard technique for adding items to a dictionary, including the Python 3.9+ merge operators, with practical notes on when each approach is best.

What Is a Python Dictionary?

A dictionary stores data as key-value pairs inside curly braces {}. Keys must be unique and immutable (strings, numbers, or tuples); values can be any Python object.

# A simple dictionary
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

Keys are unique — if you assign a value to a key that already exists, the old value is overwritten, not duplicated. Keep this behavior in mind as you work through the methods below.

Ways to Add Items to a Dictionary

Using Square Bracket Notation

The simplest way to add a new key-value pair is direct assignment with square brackets:

python— editable, runs on the server

Output:

{'name': 'John', 'age': 25, 'city': 'New York', 'gender': 'Male'}

If the key already exists the value is replaced rather than added:

my_dict = {'name': 'John', 'age': 25}

my_dict['age'] = 30  # overwrites 25

print(my_dict)
# {'name': 'John', 'age': 30}

Use square bracket assignment when you are adding or updating a single key whose name you know at write time.

Using the update() Method

dict.update() merges one or more key-value pairs into the dictionary in a single call. You can pass another dictionary, an iterable of (key, value) pairs, or keyword arguments.

Merge a second dictionary:

python— editable, runs on the server

Output:

{'name': 'John', 'age': 25, 'city': 'New York', 'gender': 'Male', 'occupation': 'Software Engineer'}

Use keyword arguments to add multiple keys at once:

my_dict = {'name': 'John', 'age': 25}

my_dict.update(city='New York', gender='Male')

print(my_dict)
# {'name': 'John', 'age': 25, 'city': 'New York', 'gender': 'Male'}

Like square bracket assignment, update() overwrites existing keys. Use it when you need to add or refresh multiple entries at once.

Using the setdefault() Method

dict.setdefault(key, default) adds a key only if it is not already present. If the key exists, it returns the existing value without changing anything.

python— editable, runs on the server

Output:

{'name': 'John', 'age': 25, 'city': 'New York', 'gender': 'Male'}

When the key already exists, setdefault() leaves it untouched and returns the current value:

my_dict = {'name': 'John', 'age': 25}

result = my_dict.setdefault('name', 'Alice')

print(result)   # John  — not overwritten
print(my_dict)  # {'name': 'John', 'age': 25}

setdefault() is the right tool when you want to initialize a key with a fallback value without accidentally overwriting data that is already there. A common pattern is initializing a missing key to an empty list before appending to it:

groups = {}

for item in ['apple', 'banana', 'avocado']:
    letter = item[0]
    groups.setdefault(letter, []).append(item)

print(groups)
# {'a': ['apple', 'avocado'], 'b': ['banana']}

Using the Merge Operators (Python 3.9+)

Python 3.9 added two operators that provide a concise syntax for combining dictionaries.

| — create a new merged dictionary (non-destructive):

d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}

d3 = d1 | d2  # d1 and d2 are unchanged

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

|= — update in place (equivalent to update() but shorter):

d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}

d1 |= d2  # d1 is modified

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

When keys overlap, the right-hand operand wins — same precedence as update(). These operators require Python 3.9 or later; use update() for broader compatibility.

Using dict.fromkeys() to Pre-populate a Dictionary

dict.fromkeys(keys, default) is a class method that creates a brand-new dictionary from an iterable of keys and an optional default value. It does not add items to an existing dictionary.

# Create a dictionary with a shared default value
template = dict.fromkeys(['name', 'age', 'city'], 'Unknown')

print(template)
# {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}

# You can then populate it with real values
template['name'] = 'Alice'
template['age'] = 28

print(template)
# {'name': 'Alice', 'age': 28, 'city': 'Unknown'}

fromkeys() is useful for scaffolding a dictionary when you know the keys in advance but will fill in values later.

Choosing the Right Method

GoalMethod
Add or overwrite a single keydict[key] = value
Add or overwrite multiple keysdict.update(...) or dict |= other (3.9+)
Add a key only if absentdict.setdefault(key, default)
Merge two dicts into a thirdnew = a | b (3.9+)
Create a new dict from a list of keysdict.fromkeys(keys, default)

Practice

Practice
Which of the following are valid ways to add a new key-value pair to an existing Python dictionary?
Which of the following are valid ways to add a new key-value pair to an existing Python dictionary?
Was this page helpful?