Python Dictionary Add New Key: Step-by-Step Guide
In this article
You add a new key to a Python dictionary by assigning a value to it with square brackets: my_dict['new_key'] = value. If the key does not exist, Python creates it; if it already exists, the value is overwritten. That one line is the standard, fastest way to add a single key. For adding several keys at once, use update(), and for conditional or computed additions, use setdefault() or a loop. This guide walks through each method, shows what can go wrong, and explains when to use which approach.
What You'll Need
- A working Python installation (any version from 3.6 onward behaves the same for these operations; dictionary ordering is guaranteed from 3.7).
- A text editor or IDE to write and run your script.
- Basic familiarity with Python syntax: variables, strings, and function calls.
Step-by-Step
- Create or identify your dictionary. Start with an existing dictionary or an empty one. For example:
user = {'name': 'Alex', 'age': 30}oruser = {}. - Add a single key with bracket assignment. Write the dictionary name, then the new key in square brackets, then an equals sign and the value:
user['email'] = 'alex@example.com'. This works for any hashable key type (strings, numbers, tuples) and any value type. - Verify the addition. Print the dictionary:
print(user). You should see the new key-value pair included. If the key already existed, the old value is replaced silently. - Add multiple keys at once with
update(). Pass a dictionary or an iterable of key-value pairs:user.update({'city': 'Berlin', 'active': True}). This adds each pair, overwriting any existing keys. You can also pass keyword arguments:user.update(country='Germany'). - Add a key only if it is missing with
setdefault(). Calluser.setdefault('role', 'member'). If 'role' is absent, it is added with the value 'member'; if present, nothing changes and the existing value is returned. This is useful for defaults. - Add keys from a loop or comprehension. For computed keys, iterate and assign:
for i in range(3): user[f'key{i}'] = i. For a new dictionary from two lists, usedict(zip(keys, values)). - Handle nested dictionaries carefully. To add a key inside a nested dictionary, access the inner dictionary first:
user['address']['zip'] = '10115'. If 'address' does not exist, this raises a KeyError; create it first withuser['address'] = {}. - Test edge cases. Try adding a key that already exists to confirm overwrite behavior, and try adding a non-hashable key (like a list) to see the TypeError. This builds intuition for what the methods do.
Common Mistakes
- Using a non-hashable key. Keys must be hashable (strings, numbers, tuples of hashables). Lists and dictionaries cannot be keys; you will get
TypeError: unhashable type. - Assuming
setdefault()overwrites. It does not; it only adds when the key is missing. Use bracket assignment orupdate()to overwrite. - Forgetting that
update()mutates in place. It returnsNone, not a new dictionary. Assigning its result to a variable gives youNone. - Accessing a missing nested key.
user['address']['zip']fails if 'address' is absent. Check with'address' in useror useuser.setdefault('address', {})['zip'] = '10115'. - Modifying a dictionary while iterating over it. Adding keys inside a
for key in my_dictloop raisesRuntimeError: dictionary changed size during iteration. Iterate over a copy (list(my_dict)) or build a new dictionary.
Tips
- Use bracket assignment for one-off additions; it is the most readable and fastest for a single key.
- Use
update()when merging another dictionary or adding several keys in one call. - Use
setdefault()for optional defaults, especially when building nested structures. - Remember that from Python 3.7, dictionaries preserve insertion order, so new keys appear at the end unless you reorder explicitly.
- For very large dictionaries, bracket assignment and
update()are both efficient; avoid repeatedsetdefault()calls in tight loops if you know the key is missing.
Troubleshooting
If your new key does not appear, check that you assigned to the correct variable and that you are not working on a copy. If you see a KeyError when adding to a nested dictionary, create the parent dictionary first. If you get TypeError: unhashable type, switch to a hashable key such as a string or tuple. If update() seems to do nothing, confirm you are not assigning its return value (it returns None). If you get a RuntimeError about dictionary size changing during iteration, iterate over a list of keys instead. For unexpected overwrites, search your code for other assignments to the same key; the last assignment wins.
Frequently Asked Questions
Can I add a key to a dictionary without a value?
No. Every key must have a value. You can use None as a placeholder: my_dict['key'] = None.
What happens if I add a key that already exists?
Bracket assignment and update() overwrite the existing value. setdefault() leaves it unchanged and returns the current value.
How do I add multiple keys from a list?
Use a loop or a dictionary comprehension: my_dict.update({k: default for k in keys}), or iterate and assign each key.
Is there a difference between my_dict[key] = value and my_dict.update({key: value})?
For a single key, they behave the same. update() is more convenient for multiple pairs and accepts keyword arguments.
Can I use a tuple as a dictionary key?
Yes, as long as all elements in the tuple are hashable. Tuples containing lists are not hashable and will raise a TypeError.
Why does my dictionary lose order when I add keys?
In Python 3.6 and earlier, dictionaries did not guarantee insertion order. From 3.7 onward, order is preserved. If you need ordered behavior on older versions, use collections.OrderedDict.