Updating a dictionary in Python means changing the value of an existing key, adding a new key-value pair, or merging another dictionary into it. This is a core operation in Python programming, and there are several clean, readable ways to do it. The most direct method is to assign to a key: my_dict['key'] = new_value. This guide covers the standard update methods, including dict.update(), the ** merge operator, and the newer | operator, with clear examples and common pitfalls.
What You’ll Need
- Python 3.5 or later (for most examples; the
|operator requires Python 3.9+, and the**merge works in 3.5+). - A Python interpreter or a script file where you can run code.
- Basic familiarity with Python syntax (variables, print statements).
Step-by-Step
- Start with a dictionary. For example:
user = {'name': 'Alice', 'age': 30}. - Update a single key’s value. Use square bracket assignment:
user['age'] = 31. This changes the value if the key exists, or adds a new key if it doesn’t. For instance,user['city'] = 'New York'adds a new key. - Update multiple keys at once. Use the
update()method with a dictionary, keyword arguments, or an iterable of key-value pairs. Example:user.update({'age': 32, 'city': 'Boston'}). This modifies the dictionary in place. - Merge two dictionaries. In Python 3.9+, you can use the union operator
|:merged = user | other_dict. This creates a new dictionary; it does not modify the originals. For in-place merging, useuser |= other_dict. - Merge using dictionary unpacking (Python 3.5+). Create a new dictionary:
merged = {**user, **other_dict}. This is a common idiom and works in older versions too. - Update from a list of key-value pairs. Use
update()with a list of tuples:user.update([('age', 33), ('city', 'Chicago')]). - Update conditionally. If you only want to update when a key doesn’t exist, use
setdefault():user.setdefault('country', 'USA')sets the value only if the key is missing. - Remove a key. To delete a key, use
del user['key']oruser.pop('key'). This is often part of an update workflow.
Common Mistakes
- Forgetting that
update()modifies in place. It returnsNone, so assigning its result to a variable gives youNone. - Using
|on Python versions before 3.9. This raises aTypeError. - Assuming
|modifies the original. It returns a new dictionary; if you want in-place, use|=. - Overwriting keys unintentionally. When merging, later dictionaries override earlier ones. If you want to keep original values, swap the order.
- Using
update()with a single argument that is not a dictionary or iterable. For example, passing an integer causes aTypeError.
Tips
- For a single key, direct assignment is the fastest and most readable.
- For merging, prefer the
|operator in Python 3.9+ for clarity; it’s the most explicit. - Use
dict.update()when you want to modify the original dictionary in place, especially in loops. - If you need to update a dictionary without changing the original, always create a copy first:
new_dict = original.copy()then update. - Remember that dictionary keys must be immutable (strings, numbers, tuples).
Troubleshooting
- Getting a
TypeErroron|. Check your Python version; upgrade to 3.9 or later, or use{**dict1, **dict2}. update()doesn’t seem to change the dictionary. Verify you’re not assigning the result ofupdate()to a variable; it modifies in place, so just calldict.update(...).- Accidentally creating a new dictionary when you wanted to modify the original. If you use
|or{**}, the original remains unchanged. Use|=orupdate()for in-place. - KeyError when trying to update a key that doesn’t exist? Direct assignment (
dict[key] = value) adds the key, so no error. If you get a KeyError, you’re probably trying to read it, not update it. - Merging two dictionaries but losing data. Check the order: the right-side dictionary overrides the left. If you want the left to override, swap them.
Frequently Asked Questions
Q: What is the difference between update() and |?
A: update() modifies the dictionary in place and returns None. The | operator (Python 3.9+) returns a new dictionary with the merged contents, leaving the originals unchanged. Use |= for in-place merging with the operator.
Q: Can I update a dictionary with another dictionary that has nested dictionaries?
A: Yes, but the merge is shallow. The inner dictionaries are not merged recursively; the value of the right-side key replaces the left’s value entirely. For deep merging, you need to write a recursive function or use a library like copy.deepcopy and manual logic.
Q: How do I update a dictionary in a loop?
A: You can use update() inside the loop to accumulate changes, or assign directly to keys. For example: for k, v in new_data.items(): my_dict[k] = v.
Q: Is there a way to update only if the key is not already present?
A: Yes, use setdefault(key, default). It sets the value only if the key is missing, and returns the existing value if present.
Q: What happens if I update a dictionary while iterating over it?
A: Modifying the size of a dictionary during iteration can raise a RuntimeError. To avoid this, iterate over a copy: for key in list(my_dict): or collect changes and apply after the loop.
Q: Can I update a dictionary with keyword arguments?
A: Yes, update() accepts keyword arguments: user.update(age=34, city='Denver'). This is a clean way to update several keys that are valid Python identifiers.
Related
- Excel Travel Expense Tracking Template: How to Build One
- Excel to Notepad Converter Online: How to Convert
- Excel Timesheet Template for Multiple Projects
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Best Free Excel Budget Templates for Monthly PlanningThe Microsoft Personal Monthly Budget template is the best free Excel budget template for most people because it…
- COUNTIF TRUE in Google Sheets: Count Boolean ValuesTo count cells whose value is the Boolean TRUE in Google Sheets, use =COUNTIF(A2:A20,TRUE), replacing A2:A20 with your…
- Sum in Excel From Different Sheets: A Step-by-Step GuideTo add the same cell from several sheets in Excel, enter a SUM formula such as =SUM(Jan!B2,Feb!B2,Mar!B2) in…
- Custom Number Format Excel Shortcut and How to Use ItIn Excel for Microsoft 365 on Windows, select the cells and press Ctrl+1 to open Format Cells, then…
- How to Double Space Bullet Points in Microsoft WordTo double-space bullet points in Microsoft Word, select the bullet paragraphs, then choose Home > Line and Paragraph…
- Excel Shortcut: How to Jump to the End of a ColumnIn Excel for Microsoft 365 on Windows, press Ctrl+Down Arrow to jump to the lower edge of the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.