How to Update a Dictionary in Python

How-to basics · Updated November 23, 2026

Updating a dictionary in Python means changing the value of an existing key, adding a new key-value pair, or modifying multiple entries at once. The simplest way is to assign a new value to a key: my_dict['key'] = new_value. This guide covers all common update methods, including update(), setdefault(), and dictionary merging, with clear examples and troubleshooting.

What You’ll Need

  • Python 3.6 or later (most examples work in 3.x; some syntax like dict merging with | requires 3.9+).
  • A Python interpreter (IDLE, terminal, or an IDE like VS Code or PyCharm).
  • Basic familiarity with Python syntax, especially variables and print().

Step-by-Step

  1. Start with a dictionary. Create a dictionary to work with. For example: user = {'name': 'Alice', 'age': 30, 'city': 'New York'}. You can also start with an empty one: data = {}.
  2. Update a single existing key. Use square bracket assignment: user['age'] = 31. This changes the value of ‘age’ to 31. If the key does not exist, this adds a new key-value pair. Example: user['email'] = 'alice@example.com' adds ’email’.
  3. Use the update() method for multiple updates. Call dict.update(iterable) where iterable is another dictionary, a list of key-value tuples, or keyword arguments. For example: user.update({'city': 'Boston', 'age': 32}) updates both keys. Or: user.update([('country', 'USA'), ('active', True)]). Or: user.update(phone='555-1234') (note: keys must be strings for keyword arguments).
  4. Add a key only if it does not exist using setdefault(). user.setdefault('role', 'member') sets ‘role’ to ‘member’ if ‘role’ is not already in the dictionary. If it exists, it leaves the value unchanged and returns the existing value. This is useful for defaults.
  5. Use dictionary unpacking (Python 3.5+). Create a new dictionary by merging: new_user = {**user, 'age': 33, 'verified': True}. This creates a copy with ‘age’ updated and ‘verified’ added. The original user remains unchanged.
  6. Use the merge operator (Python 3.9+). Combine two dictionaries with |: merged = user | {'age': 34, 'plan': 'premium'}. The result is a new dictionary; the original is not modified. To update in place, use user |= {'age': 34}.
  7. Update nested dictionaries carefully. If a value is itself a dictionary, assigning directly replaces the whole inner dictionary. To update a nested key, first access the inner dictionary: user['profile'] = {'bio': 'Hello'} then user['profile']['bio'] = 'Hi there'. Or use user.setdefault('profile', {})['bio'] = 'Hi there' to avoid KeyError.
  8. Remove a key if needed (optional). While not strictly an update, you might want to replace a key by deleting and re-adding: del user['old_key'] then user['new_key'] = value. Or use user.pop('old_key', None) to remove and get the value.

Common Mistakes

  • Using update() with a non-iterable. update(123) raises TypeError. Only pass dictionaries, lists of tuples, or keyword arguments.
  • Assuming setdefault() overwrites. It does not; it only sets if the key is missing. If you need to overwrite, use simple assignment.
  • Modifying a dictionary while iterating over it. For example, for k in user: user[k] = 1 is okay for changing values, but adding or removing keys during iteration raises RuntimeError. Iterate over a copy: for k in list(user.keys()):.
  • Confusing | with | bitwise OR on sets. In Python 3.9+, | on dicts is merge, not bitwise.
  • Updating a nested dictionary incorrectly. user['profile'] = {'bio': 'new'} replaces the entire profile, not just the ‘bio’ field. Always access the inner dict first.

Tips

  • Use update() for bulk changes. It is more readable than multiple assignments.
  • Prefer setdefault() for default values. It avoids a check-then-set pattern and is thread-safe in single-threaded code.
  • When merging, consider which dictionary takes precedence. In {**a, **b} and a | b, keys from the right operand overwrite those from the left.
  • Use dict.update() with keyword arguments for simple string keys. Example: user.update(name='Bob').
  • For nested updates, use collections.defaultdict if you frequently add inner keys. Example: from collections import defaultdict; d = defaultdict(dict); d['user']['age'] = 30 works without pre-initializing.
  • Remember that dictionaries are mutable. Assigning a dictionary to another variable does not copy it; both refer to the same object. To copy, use copy() or deepcopy() for nested structures.

Troubleshooting

  • KeyError when updating a nested key. This happens when the inner dictionary does not exist. Solution: use setdefault() or check with if 'profile' in user: before updating.
  • TypeError: ‘dict’ object is not callable. This occurs if you named a variable dict and then try to call dict(). Rename your variable and restart the interpreter.
  • Update does not modify the dictionary as expected. Check if you are using update() on a copy or if the dictionary is actually a different object. Use id(my_dict) to verify.
  • Merging with | gives SyntaxError. The merge operator requires Python 3.9 or later. If you are on an older version, use {**a, **b} instead.
  • Values not updating in a loop. If you are iterating and updating, ensure you are not accidentally creating a new dictionary. For example, for k in d: d[k] = d[k] * 2 works, but d = {k: v*2 for k,v in d.items()} creates a new dict and reassigns the variable, which is fine if that’s intended.
  • Unexpected behavior with update() from a list of tuples. Make sure each tuple has exactly two elements. A tuple with one element raises ValueError.

Frequently Asked Questions

  • How do I update a dictionary value only if the key exists? Use if 'key' in my_dict: my_dict['key'] = new_value or use my_dict.setdefault('key', default) but that adds if missing. To update only if exists, check first.
  • What is the difference between update() and setdefault()? update() overwrites existing keys and adds new ones. setdefault() only sets the value if the key is missing; it never overwrites.
  • Can I update multiple keys at once without update()? Yes, you can use a loop: for k, v in {'a':1, 'b':2}.items(): my_dict[k] = v, but update() is more concise.
  • How do I update a dictionary in a list of dictionaries? Access the dictionary by index: list_of_dicts[0]['key'] = value. For example, users[0]['age'] = 25.
  • Is there a way to update a dictionary without changing the original? Yes, create a copy first: new = original.copy() then update new. For nested dicts, use copy.deepcopy().
  • What does dict.update() return? It returns None. It modifies the dictionary in place. If you need the updated dictionary, use the original variable after calling update.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.