Python Dictionaries: Adding, Updating, and Managing Key/Value Pairs
Python dictionaries are foundational data structures that store data as key/value pairs. Keys are immutable and unique, while values can be any data type, including nested structures.
Key Rules for Dictionary Keys
- Duplicate keys are overwritten: the last occurrence takes precedence.
- Allowed key types include strings, numbers, tuples, and other hashable objects. Mutable types like lists cannot be used as keys.
- Python’s built‑in functions, classes, and even functions themselves can serve as keys.
Adding Elements to a Dictionary
To add a new key/value pair, simply assign a value to a new key:
my_dict = {"username": "XYZ", "email": "xyz@example.com"}
my_dict["location"] = "Mumbai"
print(my_dict)
Output: {"username": "XYZ", "email": "xyz@example.com", "location": "Mumbai"}
When the value is a list, you can append items to that list:
my_dict = {"tags": []}
my_dict["tags"].append("python")
print(my_dict)
Output: {"tags": ["python"]}
Accessing Dictionary Elements
Retrieve a value by its key using square brackets. If the key does not exist, a KeyError is raised:
print(my_dict["username"]) # XYZ print(my_dict["nonexistent"]) # KeyError
To avoid errors, use dict.get() or dict.setdefault():
print(my_dict.get("nonexistent", "default"))
Deleting Elements
- del keyword:
del my_dict["username"] - pop() method:
removed = my_dict.pop("email")returns the removed value. - clear() method:
my_dict.clear()empties the dictionary.
Updating Existing Values
Assign a new value to an existing key to update it:
my_dict["username"] = "ABC" print(my_dict)
Combining Dictionaries
Merge two dictionaries using update() or the union operator (|) in Python 3.9+:
dict_a = {"a": 1, "b": 2}
dict_b = {"b": 3, "c": 4}
dict_a.update(dict_b)
print(dict_a) # {"a": 1, "b": 3, "c": 4}
# or
combined = dict_a | dict_b
print(combined)
Embedding a Dictionary Inside Another
Assign a whole dictionary to a new key to nest it:
parent = {"username": "XYZ"}
child = {"firstName": "Nick", "lastName": "Price"}
parent["name"] = child
print(parent)
Output: {"username": "XYZ", "name": {"firstName": "Nick", "lastName": "Price"}}
Summary
- Dictionary keys are unique, hashable, and immutable.
- Use assignment for adding or updating,
delorpop()for removal, andclear()to empty. - Methods like
update()and the union operator simplify merging dictionaries.
For more details, refer to the official Python documentation: Python Data Structures – Dictionaries.
Python
- Getting Started with Python: Install, Run, and Write Your First Program
- Python Variables, Constants, and Literals – A Comprehensive Guide
- Mastering Python Dictionaries: Creation, Manipulation, and Advanced Techniques
- Retrieve Current Date and Time in Python: A Practical Guide
- Python Print() Function: A Practical Guide with Examples
- Calculating Averages in Python: A Practical Guide
- Avoiding Common Pitfalls: Proper Exception Handling in Python
- Mastering Brand Equity: A Strategic Blueprint for Sustainable Business Value
- Python Dictionary Fundamentals: Keys, Values, and Access
- Unlocking Business Value with UID: Enhancing Asset Tracking & Compliance