Python Dictionary Methods
Dictionary Methods
Python dictionaries include built-in methods for reading, adding, updating, removing, and copying key–value data. Methods are called with dot notation:
my_dict.method_name(arguments)
This lesson is a practical reference to the eleven dictionary methods, with an example, expected output, and explanation for each.
Quick Reference
| Method | Description | Modifies the Dictionary |
|---|---|---|
clear() | Removes all items | Yes |
copy() | Returns a shallow copy | No |
fromkeys(keys, value) | Creates a new dictionary from a sequence of keys | No (class method) |
get(key, default) | Returns the value for a key, or a default if the key is missing | No |
items() | Returns a view of (key, value) pairs | No |
keys() | Returns a view of all keys | No |
pop(key, default) | Removes a key and returns its value | Yes |
popitem() | Removes and returns the last inserted pair | Yes |
setdefault(key, default) | Returns a key's value; inserts the key with a default if missing | Sometimes |
update(other) | Adds or overwrites items from another dictionary or iterable | Yes |
values() | Returns a view of all values | No |
clear()
Removes all items, leaving an empty dictionary.
cart = {"item": "Shoes", "price": 2999}
cart.clear()
print(cart)
Expected output:
{}
The dictionary object still exists; it is simply empty.
copy()
Returns a new, separate dictionary with the same key–value pairs.
profile = {"username": "max_m", "followers": 120}
backup_profile = profile.copy()
profile["followers"] = 150
print(profile)
print(backup_profile)
Expected output:
{'username': 'max_m', 'followers': 150}
{'username': 'max_m', 'followers': 120}
Changing profile does not affect backup_profile, because they are different objects. (With backup_profile = profile, both names would refer to the same dictionary.)
Note:
copy()is shallow. Nested lists or dictionaries inside the values are shared between the copies. Usecopy.deepcopy()for fully independent nested data.
fromkeys()
Creates a new dictionary from a sequence of keys, giving every key the same starting value. It is called on the dict class itself.
subjects = ["Math", "Science", "English"]
marks = dict.fromkeys(subjects, 0)
print(marks)
Expected output:
{'Math': 0, 'Science': 0, 'English': 0}
If you omit the value, every key gets None:
print(dict.fromkeys(["a", "b"]))
Expected output:
{'a': None, 'b': None}
Caution: If the default value is mutable (such as a list), all keys share the same object.
dict.fromkeys(["a", "b"], [])creates one list used by both keys, so appending to one appears under both. Use a dictionary comprehension instead:{key: [] for key in ["a", "b"]}.
get()
Returns the value for a key. If the key does not exist, it returns None — or the default value you supply — instead of raising a KeyError.
user = {"name": "Aisha", "age": 22}
print(user.get("age"))
print(user.get("email"))
print(user.get("email", "not provided"))
Expected output:
22
None
not provided
Compare with square brackets, which raise an error for a missing key:
print(user["email"])
Output:
KeyError: 'email'
get() is ideal for optional data, such as fields that may or may not be present in a form submission or API response.
items()
Returns a view object of all key–value pairs, each as a tuple.
scores = {"Tom": 85, "Jerry": 90}
print(scores.items())
Expected output:
dict_items([('Tom', 85), ('Jerry', 90)])
items() is most often used to loop through keys and values together:
for name, score in scores.items():
print(f"{name} scored {score}")
Expected output:
Tom scored 85
Jerry scored 90
keys()
Returns a view object of all keys.
settings = {"theme": "dark", "language": "English"}
print(settings.keys())
Expected output:
dict_keys(['theme', 'language'])
What Is a View Object?
The objects returned by keys(), values(), and items() are views: live windows into the dictionary rather than copies. If the dictionary changes, the view shows the change.
settings = {"theme": "dark", "language": "English"}
keys_view = settings.keys()
settings["font_size"] = 14
print(keys_view)
Expected output:
dict_keys(['theme', 'language', 'font_size'])
To get a fixed list instead, use list(settings.keys()).
pop()
Removes the item with the given key and returns its value.
inventory = {"pen": 10, "pencil": 20}
removed = inventory.pop("pen")
print(removed)
print(inventory)
Expected output:
10
{'pencil': 20}
If the key does not exist, pop() raises a KeyError — unless you provide a default value:
inventory = {"pencil": 20}
print(inventory.pop("eraser", 0))
Expected output:
0
popitem()
Removes and returns the last inserted key–value pair as a tuple (Python 3.7+).
orders = {"order1": 250, "order2": 450}
last_order = orders.popitem()
print(last_order)
print(orders)
Expected output:
('order2', 450)
{'order1': 250}
Calling popitem() on an empty dictionary raises a KeyError.
setdefault()
Returns the value of a key. If the key does not exist, it inserts the key with the given default value and returns that default.
config = {"mode": "auto"}
timeout = config.setdefault("timeout", 30)
print(timeout)
print(config)
Expected output:
30
{'mode': 'auto', 'timeout': 30}
If the key already exists, its value is not changed:
config = {"mode": "auto"}
print(config.setdefault("mode", "manual"))
print(config)
Expected output:
auto
{'mode': 'auto'}
Practical Use: Grouping Items
setdefault() is handy when building a dictionary of lists:
students = [("Asha", "A"), ("Ravi", "B"), ("Meena", "A")]
groups = {}
for name, grade in students:
groups.setdefault(grade, []).append(name)
print(groups)
Expected output:
{'A': ['Asha', 'Meena'], 'B': ['Ravi']}
The first time a grade is seen, setdefault() creates an empty list for it; afterwards, it returns the existing list, and append() adds the name.
update()
Adds new key–value pairs and overwrites existing ones, using another dictionary or an iterable of pairs.
employee = {"name": "Rahul", "role": "Developer"}
employee.update({"role": "Senior Developer", "salary": 80000})
print(employee)
Expected output:
{'name': 'Rahul', 'role': 'Senior Developer', 'salary': 80000}
"role"already existed, so its value was replaced."salary"was new, so it was added.
update() also accepts keyword arguments: employee.update(location="Pune").
Tip: From Python 3.9 onward, the
|operator merges two dictionaries into a new one (merged = a | b), and|=updates a dictionary in place.
values()
Returns a view object of all values.
prices = {"apple": 120, "banana": 40}
print(prices.values())
Expected output:
dict_values([120, 40])
The values view works well with built-in functions:
prices = {"apple": 120, "banana": 40, "mango": 90}
print(sum(prices.values()))
print(max(prices.values()))
Expected output:
250
120
Practical Example: Shopping Cart
This example combines several methods:
cart = {}
cart.update({"notebook": 2, "pen": 5})
cart["pencil"] = cart.get("pencil", 0) + 3 # Add 3 pencils
cart["pen"] = cart.get("pen", 0) + 1 # Add 1 more pen
cart.pop("notebook") # Remove notebooks
for item, quantity in cart.items():
print(f"{item}: {quantity}")
print("Total items:", sum(cart.values()))
Expected output:
pen: 6
pencil: 3
Total items: 9
The pattern cart.get(key, 0) + n safely increases a count whether or not the key already exists.
Common Mistakes
| Mistake | Problem | Better Approach |
|---|---|---|
d["key"] for an optional key | KeyError if missing | d.get("key", default) |
dict.fromkeys(keys, []) | All keys share one list | {k: [] for k in keys} |
backup = d to copy | Both names refer to the same dictionary | backup = d.copy() |
Expecting keys() to return a list | It returns a live view | list(d.keys()) |
d.pop("x") for a key that may be missing | KeyError | d.pop("x", None) |
Related Concepts
- Python Dictionaries — creating, accessing, looping, and nesting dictionaries
- Python JSON — converting dictionaries to and from JSON
- Python For Loops — looping with
keys(),values(), anditems()