Python
dictionary
programming
coding
data-structures

Add a new item to a dictionary in Python

Master System Design with Codemia

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

Introduction

Adding items to a Python dictionary is done with bracket assignment (d[key] = value), the update() method, the merge operator (|=, Python 3.9+), or setdefault() for conditional insertion. Dictionaries are mutable hash maps with O(1) average-case insertion and lookup. Keys must be hashable (strings, numbers, tuples of immutables), while values can be any object. This article covers all insertion methods with practical examples.

Bracket Assignment (Most Common)

python
1user = {"name": "Alice", "age": 30}
2
3# Add a new key-value pair
4user["email"] = "[email protected]"
5print(user)
6# {'name': 'Alice', 'age': 30, 'email': '[email protected]'}
7
8# Overwrite an existing key
9user["age"] = 31
10print(user["age"])  # 31

Bracket assignment adds the key if it doesn't exist, or overwrites the value if it does. This is the most common and most readable approach.

The update() Method

python
1user = {"name": "Alice"}
2
3# Add multiple items at once with a dictionary
4user.update({"age": 30, "email": "[email protected]"})
5print(user)
6# {'name': 'Alice', 'age': 30, 'email': '[email protected]'}
7
8# Add items using keyword arguments
9user.update(city="Portland", active=True)
10print(user)
11# {'name': 'Alice', 'age': 30, 'email': '[email protected]', 'city': 'Portland', 'active': True}
12
13# Add items from a list of tuples
14extra = [("role", "admin"), ("level", 5)]
15user.update(extra)
16print(user["role"])  # admin

update() accepts a dictionary, keyword arguments, or an iterable of key-value pairs. Existing keys are overwritten by the new values.

Merge Operator (Python 3.9+)

python
1defaults = {"theme": "light", "lang": "en"}
2overrides = {"theme": "dark", "font_size": 14}
3
4# | creates a new merged dictionary
5merged = defaults | overrides
6print(merged)
7# {'theme': 'dark', 'lang': 'en', 'font_size': 14}
8
9# |= updates in place
10defaults |= overrides
11print(defaults)
12# {'theme': 'dark', 'lang': 'en', 'font_size': 14}

The | operator creates a new dictionary. The |= operator updates the left dictionary in place. Both give priority to the right-hand operand for duplicate keys.

setdefault() for Conditional Insertion

python
1config = {"host": "localhost"}
2
3# Only adds the key if it doesn't already exist
4config.setdefault("port", 8080)
5print(config)  # {'host': 'localhost', 'port': 8080}
6
7# Key already exists — value is NOT overwritten
8config.setdefault("host", "0.0.0.0")
9print(config["host"])  # localhost (unchanged)
10
11# Useful for building grouped data
12from collections import defaultdict
13
14data = [("fruit", "apple"), ("veggie", "carrot"), ("fruit", "banana")]
15grouped = {}
16for category, item in data:
17    grouped.setdefault(category, []).append(item)
18print(grouped)
19# {'fruit': ['apple', 'banana'], 'veggie': ['carrot']}

setdefault(key, default) returns the existing value if the key exists, or inserts default and returns it if the key is missing. It's ideal for building lists or nested structures without checking key existence first.

Dictionary Comprehension

python
1# Create a dictionary from two lists
2keys = ["name", "age", "city"]
3values = ["Alice", 30, "Portland"]
4user = {k: v for k, v in zip(keys, values)}
5print(user)  # {'name': 'Alice', 'age': 30, 'city': 'Portland'}
6
7# Add computed entries
8squares = {x: x**2 for x in range(6)}
9print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
10
11# Merge and transform
12base = {"a": 1, "b": 2}
13extra = {"c": 3, "d": 4}
14combined = {k: v * 10 for d in [base, extra] for k, v in d.items()}
15print(combined)  # {'a': 10, 'b': 20, 'c': 30, 'd': 40}

Nested Dictionary Insertion

python
1users = {}
2
3# Add a nested dictionary
4users["alice"] = {"age": 30, "email": "[email protected]"}
5
6# Add to a nested dictionary
7users["alice"]["city"] = "Portland"
8print(users)
9# {'alice': {'age': 30, 'email': '[email protected]', 'city': 'Portland'}}
10
11# Safe nested insertion
12users.setdefault("bob", {})["age"] = 25
13print(users["bob"])  # {'age': 25}

Common Pitfalls

  • Accidental key overwrite: Bracket assignment silently overwrites existing keys. Use setdefault() or check if key not in d when you want to preserve existing values.
  • Unhashable keys: Lists, sets, and dictionaries cannot be dictionary keys because they are mutable. Use tuples instead of lists if you need a composite key.
  • Mutating during iteration: Adding or removing keys while iterating over a dictionary raises RuntimeError. Create a copy first (for k in list(d.keys())) or collect changes and apply them after the loop.
  • Confusing update() overwrite behavior: update() silently overwrites existing keys with new values. If you need to merge without overwriting, use setdefault() or conditional logic.
  • Forgetting |= requires Python 3.9+: The merge operator (| and |=) is only available in Python 3.9 and later. Use update() or {**d1, **d2} for older versions.

Summary

  • d[key] = value — add or overwrite a single key (most common)
  • d.update(other) — add multiple keys from a dict, keyword args, or iterable of pairs
  • d |= other — merge operator for in-place update (Python 3.9+)
  • d.setdefault(key, default) — insert only if key is missing
  • Dictionary comprehension — create or transform dictionaries from iterables
  • Keys must be hashable; values can be any type

Course illustration
Course illustration

All Rights Reserved.