Python Dictionary Methods
Python dictionaries come with a set of built-in methods for reading, updating, copying, and cleaning up their contents.
The built-in dictionary methods
Every dictionary shares the same collection of methods. The table below summarizes what each one does so you can pick the right tool for the task at hand.
setdefault in action
setdefault() is useful when you want to read a key but also guarantee it exists. If the key is missing, it is inserted with the default value and that value is returned.
Using setdefault()
user = {"name": "Sam"}
role = user.setdefault("role", "guest")
print(role) # guest
print(user) # {'name': 'Sam', 'role': 'guest'}Copying safely
Assigning one dictionary to another variable does not create a new dictionary; both names point to the same object. Use copy() when you want an independent duplicate that can change without affecting the original.
copy() versus assignment
original = {"a": 1, "b": 2}
same = original # same object
clone = original.copy() # independent copy
clone["a"] = 99
print(original["a"]) # 1, unchanged
print(clone["a"]) # 99Note: copy() makes a shallow copy. If your values are themselves lists or dictionaries, both copies still share those nested objects; use copy.deepcopy() for a fully independent duplicate.
fromkeys() for defaults
fields = ["name", "email", "phone"]
blank = dict.fromkeys(fields, "")
print(blank) # {'name': '', 'email': '', 'phone': ''}- get() and setdefault() help you handle missing keys gracefully.
- update() and pop() are the workhorses for editing entries.
- copy() protects the original when you need a separate version.
- fromkeys() quickly scaffolds a dictionary with default values.