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.

MethodDescription
get(key, default)Returns the value for key, or default if the key is missing
keys()Returns a view of all keys
values()Returns a view of all values
items()Returns a view of all key-value pairs
update(other)Merges another dictionary or pairs into this one
pop(key)Removes key and returns its value
popitem()Removes and returns the last inserted pair
setdefault(key, default)Returns the value if present, otherwise inserts and returns default
copy()Returns a shallow copy of the dictionary
clear()Removes all items
fromkeys(keys, value)Builds a new dictionary from a list of keys with one shared value

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"])     # 99
Note: 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.