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
- 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 = {}. - 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’. - Use the
update()method for multiple updates. Calldict.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). - 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. - 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 originaluserremains unchanged. - 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, useuser |= {'age': 34}. - 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'}thenuser['profile']['bio'] = 'Hi there'. Or useuser.setdefault('profile', {})['bio'] = 'Hi there'to avoid KeyError. - 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']thenuser['new_key'] = value. Or useuser.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] = 1is 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}anda | 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.defaultdictif you frequently add inner keys. Example:from collections import defaultdict; d = defaultdict(dict); d['user']['age'] = 30works 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()ordeepcopy()for nested structures.
Troubleshooting
- KeyError when updating a nested key. This happens when the inner dictionary does not exist. Solution: use
setdefault()or check withif 'profile' in user:before updating. - TypeError: ‘dict’ object is not callable. This occurs if you named a variable
dictand then try to calldict(). 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. Useid(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] * 2works, butd = {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_valueor usemy_dict.setdefault('key', default)but that adds if missing. To update only if exists, check first. - What is the difference between
update()andsetdefault()?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, butupdate()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 updatenew. For nested dicts, usecopy.deepcopy(). - What does
dict.update()return? It returnsNone. It modifies the dictionary in place. If you need the updated dictionary, use the original variable after calling update.
Related
- How to Select All on a Dell Laptop: 5 Ways
- Shortcut for Format Cells in Excel (Windows & Mac)
- Porter-Cable PCE201 Impact Driver Review & Specs
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Create a New Signature in Outlook 365, Step by StepTo create a new signature in Outlook 365, open the signature settings for your version of Outlook, choose…
- How to Change Slide Size in PowerPoint to A4 PaperTo change a PowerPoint presentation to A4, open it in the desktop app, select Design > Slide Size…
- Excel Quick Border: Add Cell Borders Fast in Microsoft 365In Excel for Microsoft 365 on Windows, select the cell or range and press Ctrl+Shift+& to apply an…
- Excel Scatter Plot Series Colors: How to Change ThemTo change a scatter plot series color in Excel for Microsoft 365 on Windows, right-click a marker in…
- Google Sheets GOOGLETRANSLATE Function: How It WorksGoogle Sheets includes a built-in GOOGLETRANSLATE function for translating text in a cell. For example, if A2 contains…
- Find and Replace in Excel: Select Data FirstTo find and replace text in only part of an Excel worksheet, select the cells or range first,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.