Python Dictionary Methods
Table of Contents
In the last lesson, we learned about Python Dictionary Operations. Now letβs use dictionary methods to access, update, and remove data safely.
π§© Letβs Talk About Tools for Dictionaries
We have a dictionary. We know how to access values. We know how to add and remove items.
But there are many built-in methods that make working with dictionaries easier. These are functions that belong to dictionary objects. They let us do things like get values safely, update multiple items, remove items, copy the dictionary, and more.
Letβs go through the most common dictionary methods.
βοΈ Getting Values Safely β get() in Python
The get() method returns the value for a key. If the key does not exist, it returns None instead of raising an error. We can also provide a default value.
person = {"name": "Alex", "age": 25}print(person.get("name"))print(person.get("city"))print(person.get("city", "Unknown"))Output
AlexNoneUnknownThis is safer than using square brackets. Letβs use it when we are not sure if the key exists.
π‘ Setting a Default β setdefault() in Python
setdefault() returns the value for a key. If the key does not exist, it inserts the key with a default value and returns that default.
person = {"name": "Alex", "age": 25}person.setdefault("city", "London")print(person)Output
{'name': 'Alex', 'age': 25, 'city': 'London'}If the key already exists, setdefault() does nothing and returns the existing value.
person.setdefault("name", "Sam")print(person["name"])Output
AlexThe name is still βAlexβ. Because it already existed.
π§ͺ Getting All Keys, Values, and Items in Python
Dictionaries have three view methods.
keys()returns a view of all keys.values()returns a view of all values.items()returns a view of all key-value pairs as tuples.
person = {"name": "Alex", "age": 25, "city": "London"}print(person.keys())print(person.values())print(person.items())Output
dict_keys(['name', 'age', 'city'])dict_values(['Alex', 25, 'London'])dict_items([('name', 'Alex'), ('age', 25), ('city', 'London')])These are not lists. They are view objects. But we can loop over them, or convert them to lists if needed.
print(list(person.keys()))Output
['name', 'age', 'city']They are dynamic. If we change the dictionary, the view updates.
π Updating a Dictionary β update() in Python
The update() method adds all key-value pairs from another dictionary or iterable of key-value pairs. It modifies the dictionary in place.
dict1 = {"a": 1, "b": 2}dict2 = {"b": 3, "c": 4}dict1.update(dict2)print(dict1)Output
{'a': 1, 'b': 3, 'c': 4}We can also update with an iterable of pairs.
dict1.update([("d", 5), ("e", 6)])print(dict1)Output
{'a': 1, 'b': 3, 'c': 4, 'd': 5, 'e': 6}ποΈ Removing Items β pop(), popitem(), clear() in Python
pop(key) removes the key and returns its value. If the key is not found, it raises a KeyError, unless we provide a default.
person = {"name": "Alex", "age": 25, "city": "London"}age = person.pop("age")print(age)print(person)Output
25{'name': 'Alex', 'city': 'London'}person.pop("country", "Not found")Output
'Not found'popitem() removes and returns the last inserted key-value pair as a tuple. In Python 3.7+, it removes the last item.
person = {"name": "Alex", "age": 25, "city": "London"}item = person.popitem()print(item)print(person)Output
('city', 'London'){'name': 'Alex', 'age': 25}clear() removes all items.
person.clear()print(person)Output
{}π Copying a Dictionary β copy() in Python
The copy() method returns a shallow copy of the dictionary.
original = {"a": 1, "b": 2}copied = original.copy()print(copied)Output
{'a': 1, 'b': 2}We can also use dict(original). For deep copies, we use copy.deepcopy() from the copy module.
π§ Creating a Dictionary from Keys β fromkeys() in Python
fromkeys() is a class method that creates a new dictionary from a sequence of keys, all with the same value.
keys = ["a", "b", "c"]new_dict = dict.fromkeys(keys)print(new_dict)Output
{'a': None, 'b': None, 'c': None}We can provide a value.
new_dict = dict.fromkeys(keys, 0)print(new_dict)Output
{'a': 0, 'b': 0, 'c': 0}That is useful for initializing a dictionary with default values.
β οΈ Python Dictionary Methods: A Real-Life Example
Letβs build a simple inventory system.
inventory = {"apple": 10, "banana": 5}
# Add a new iteminventory["orange"] = 8print(inventory)
# Update quantityinventory["apple"] = 12print(inventory)
# Remove an iteminventory.pop("banana")print(inventory)
# Check if an item existsif "apple" in inventory: print("Apples in stock")
# Get with defaultprint(inventory.get("grape", "Out of stock"))
# Loop through itemsfor item, qty in inventory.items(): print(f"{item}: {qty}")Output
{'apple': 10, 'banana': 5, 'orange': 8}{'apple': 12, 'banana': 5, 'orange': 8}{'apple': 12, 'orange': 8}Apples in stockOut of stockapple: 12orange: 8That uses many of the methods we covered.
π Common Mistakes with Python Dictionary Methods
β Mistake 1: Using get() But Forgetting It Returns None
person = {"name": "Alex"}print(person.get("age") + 1) # Error!So what do we do? We provide a default or check for None.
print(person.get("age", 0) + 1)π« Mistake 2: Thinking update() Returns a New Dictionary
dict1 = {"a": 1}dict1 = dict1.update({"b": 2}) # dict1 becomes NoneSo what do we do? We do not assign the result.
dict1.update({"b": 2})π Mistake 3: Using pop() Without a Default on a Missing Key
person = {"name": "Alex"}person.pop("age") # Error!So what do we do? We use a default or check first.
person.pop("age", None)π Mistake 4: Confusing keys(), values(), and items()
keys()gives keys.values()gives values.items()gives key-value pairs.
Letβs use the right one for our task.
Next, we will learn about Python Nested Dictionaries and store dictionaries inside other dictionaries.