Python Dictionary Operations
Table of Contents
In the last lesson, we learned about Python Introduction to Dictionaries. Now let’s read, add, update, remove, and check dictionary items.
Let’s Do More with Dictionaries
We know how to create a dictionary. We know how to access values. We know how to add and change items.
But there is more we can do. We can merge dictionaries. We can check if a key exists. We can get values safely. We can remove items in different ways.
Let’s go through the common dictionary operations.
Checking If a Key Exists in Python
We already saw in. It checks if a key is in the dictionary.
person = {"name": "Alex", "age": 25}print("name" in person)Output
Trueprint("city" in person)Output
FalseWe can also use not in.
print("city" not in person)Output
TrueThis is very common. We will use it all the time to avoid KeyError.
Getting a Value Safely with get() in Python
If we try to access a key that does not exist, we get a KeyError. But get() is safer. It returns None if the key is not found. Or we can give it a default value.
person = {"name": "Alex", "age": 25}print(person.get("name"))Output
Alexprint(person.get("city"))Output
Noneprint(person.get("city", "Unknown"))Output
UnknownThat is very useful. Let’s use get() when we are not sure if the key exists.
Setting a Default with setdefault() in Python
setdefault() is like get(), but it also adds the key if it does not exist.
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. It returns the existing value.
person.setdefault("name", "Sam")print(person)Output
{'name': 'Alex', 'age': 25, 'city': 'London'}The name is still “Alex”. Because it already existed.
Length of a Python Dictionary
We use len() to get the number of key-value pairs.
person = {"name": "Alex", "age": 25, "city": "London"}print(len(person))Output
3Merging Dictionaries in Python
We can merge two dictionaries using the update() method.
dict1 = {"a": 1, "b": 2}dict2 = {"b": 3, "c": 4}dict1.update(dict2)print(dict1)Output
{'a': 1, 'b': 3, 'c': 4}Notice that b was overwritten. Because dict2 had a value for b. The update method takes the second dictionary’s values for any overlapping keys.
If we do not want to modify the original, we can create a new dictionary.
dict1 = {"a": 1, "b": 2}dict2 = {"b": 3, "c": 4}merged = {**dict1, **dict2}print(merged)Output
{'a': 1, 'b': 3, 'c': 4}The ** unpacks the dictionaries. This is a clean way to merge without changing the originals.
In Python 3.9 and later, we can use the | operator.
merged = dict1 | dict2print(merged)Output
{'a': 1, 'b': 3, 'c': 4}That is even cleaner. But it only works in Python 3.9+.
Copying a Python Dictionary
We can copy a dictionary using copy().
original = {"a": 1, "b": 2}copied = original.copy()print(copied)Output
{'a': 1, 'b': 2}We can also use dict().
copied = dict(original)Both create a shallow copy. If the dictionary contains mutable objects, they will be shared. For deep copies, we use copy.deepcopy().
Removing Items from a Python Dictionary
We already know del and pop(). Let’s see popitem() and clear().
popitem() removes and returns the last inserted key-value pair. 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
{}Checking Equality in Python Dictionaries
We can compare two dictionaries with ==.
dict1 = {"a": 1, "b": 2}dict2 = {"b": 2, "a": 1}print(dict1 == dict2)Output
TrueBecause dictionaries compare by content, not order.
Iterating Through Python Dictionaries
We already saw looping. But let’s recap the 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"}
for key in person.keys(): print(key)
for value in person.values(): print(value)
for key, value in person.items(): print(f"{key}: {value}")Output
nameagecityAlex25Londonname: Alexage: 25city: LondonThese views are dynamic. If we change the dictionary, the view updates.
Python Dictionary Operations: A Real-Life Example
Let’s combine dictionaries of student scores.
scores1 = {"Alex": 85, "Sam": 92}scores2 = {"John": 78, "Alex": 88}
all_scores = scores1 | scores2print(all_scores)Output
{'Alex': 88, 'Sam': 92, 'John': 78}Alex’s score was overwritten by the second dictionary.
Now let’s use get() to handle missing keys.
students = ["Alex", "Sam", "John", "Emma"]scores = {"Alex": 85, "Sam": 92, "John": 78}
for student in students: score = scores.get(student, "No score") print(f"{student}: {score}")Output
Alex: 85Sam: 92John: 78Emma: No scoreThat is a safe way to look up values.
Common Mistakes with Python Dictionary Operations
Mistake 1: Using get() Without a Default and Expecting a Value
person = {"name": "Alex"}print(person.get("age") + 1) # Error!Because get("age") returns None, and we cannot add 1 to None.
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 Noneprint(dict1)Output
Noneupdate() changes the dictionary in place and returns None. Let’s not assign the result.
Mistake 3: Using popitem() on an Empty Dictionary
empty = {}empty.popitem() # Error!So what do we do? We check if the dictionary is not empty first.
if empty: empty.popitem()Mistake 4: Confusing keys() and values()
keys() gives keys. values() gives values. Let’s make sure we use the right one.
Next, we will learn about Python Dictionary Methods and use built-in tools to work with dictionary data.