Add keys to a Python dictionary

Insert or replace dictionary entries with assignment, merge values with update, and set a default only when a key is missing.

Best practices
Add keys to a Python dictionary illustration

Assign mapping[key] = value to add an entry. If the key already exists, assignment replaces its value. Use update() to apply several entries at once.

Choose how existing keys should behave

values = {'a': 1}
values['b'] = 2
values.update({'c': 3, 'd': 4})

assert values.setdefault('a', 99) == 1  # Existing value wins
assert values.setdefault('e', 5) == 5   # Missing key is inserted

setdefault() is useful when you need the value whether the key existed or was just created. update() mutates the dictionary and returns None; do not assign its return value back to your variable.

Merge dictionaries or add conditionally

left = {'a': 1, 'shared': 'left'}
right = {'b': 2, 'shared': 'right'}
combined = left | right  # Python 3.9+
assert combined['shared'] == 'right'

if 'timeout' not in values:
    values['timeout'] = 30

The | operator creates a new dictionary, and the right-hand value wins for overlapping keys. left |= right updates left in place. Keys must be hashable; strings and suitable tuples work, while lists and dictionaries cannot be keys.

FAQ

What happens when I read a missing key?

values['missing'] raises KeyError. values.get('missing', default) returns a fallback without inserting anything. That differs from setdefault, which inserts a missing entry.

What does setdefault return?

The existing value, or the default it inserted. Python evaluates arguments before the call, so values.setdefault('key', expensive_function()) still calls the function even when the key exists. Use an explicit membership check if avoiding that computation matters.

See Python built-in types.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting