How to Add and Update Keys in a Python Dictionary
Learn how to add elements or update key-value pairs in a Python dictionary. Explore square brackets, update method, and merge operator options.
Explanation
Adding and updating elements in a dictionary is a core concept in state management, data processing, and configuration updates. Since Python dictionaries are mutable collections, you can easily modify their keys and values dynamically during program execution without needing to recreate the entire structure.
The simplest way to add a key-value pair is using square bracket assignment syntax: `my_dict[key] = value`. If the key does not exist, Python adds it to the dictionary. If the key already exists, Python overwrites its old value with the new one.
For bulk updates or merging operations, Python provides the `.update()` method, which accepts another dictionary or an iterable of key-value pairs. Additionally, in Python 3.9+, you can use the merge union operator `|` to merge two dictionaries into a new one, or the update operator `|=` to update a dictionary in-place.
Step-by-Step Implementation
- 1
Use bracket notation my_dict['new_key'] = value to insert a single new element.
- 2
Call my_dict.update(new_dict) to merge multiple keys and values in-place.
- 3
Use the | union operator in Python 3.9+ to combine dictionaries without altering the originals.
Code Example
This script demonstrates addition, updates, and merging dictionaries in Python.
profile = {"username": "sara", "level": 5}
# 1. Add new key-value pair using brackets
profile["verified"] = True
print("After adding key:", profile)
# 2. Update existing key using brackets
profile["level"] = 6
print("After updating key:", profile)
# 3. Add/Update multiple keys using update()
profile.update({"avatar": "cat.png", "level": 7})
print("After update():", profile)
# 4. Using the merge operator (Python 3.9+)
extra_info = {"location": "US"}
merged_profile = profile | extra_info
print("Merged profile:", merged_profile)After adding key: {'username': 'sara', 'level': 5, 'verified': True}
After updating key: {'username': 'sara', 'level': 6, 'verified': True}
After update(): {'username': 'sara', 'level': 7, 'verified': True, 'avatar': 'cat.png'}
Merged profile: {'username': 'sara', 'level': 7, 'verified': True, 'avatar': 'cat.png', 'location': 'US'}Frequently Asked Questions
What happens if I add a key that already exists?
The old value associated with that key is silently overwritten by the new value.
Can I add a key with a default list value if it doesn't exist?
Yes! You can use my_dict.setdefault(key, []) or use defaultdict from the collections module to automate default value initialization.
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Generators
Learn how to use Python generators and yield statements to process huge datasets with minimal memory footprints. Master generator expressions.
Python Dictionary Methods
Learn Python dictionary methods. Complete reference guide for key-value pair insertions, retrievals, updates, and checks.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.