Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Few mistakes when using Python dictionary
Dictionaries in Python are a data structure that maps keys to values as key-value pairs. They are one of the most frequently used data structures and have many useful properties. However, there are several common mistakes developers make when working with dictionaries that can lead to errors or unexpected behavior.
Basic Dictionary Operations
Before exploring common mistakes, let's review basic dictionary operations ?
# Creating a dictionary
days_dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
print(type(days_dict))
print(days_dict)
# Using the dict() constructor
days_dict2 = dict([('day1', 'Mon'), ('day2', 'Tue'), ('day3', 'Wed')])
print(days_dict2)
<class 'dict'>
{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
Common Mistake 1: Using [] Instead of get() for Key Access
Using square brackets to access dictionary values can throw a KeyError if the key doesn't exist ?
days_dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
# Risky approach - may throw KeyError
try:
print(days_dict['day4']) # This will raise KeyError
except KeyError as e:
print(f"KeyError: {e}")
# Safe approach using get()
print(days_dict.get('day4', 'Not found')) # Returns default value
print(days_dict.get('day1')) # Returns 'Mon'
KeyError: 'day4' Not found Mon
Common Mistake 2: Shallow vs Deep Copy
Assigning one dictionary to another creates a reference, not a copy. Changes to one affect the other ?
original_dict = {'day1': 'Mon', 'day2': 'Tue'}
# Wrong way - creates a reference
copy_dict = original_dict
copy_dict['day3'] = 'Wed'
print("Original:", original_dict) # Both are modified!
# Correct way - creates a shallow copy
import copy
original_dict2 = {'day1': 'Mon', 'day2': 'Tue'}
proper_copy = original_dict2.copy()
proper_copy['day3'] = 'Wed'
print("Original2:", original_dict2)
print("Copy:", proper_copy)
Original: {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
Original2: {'day1': 'Mon', 'day2': 'Tue'}
Copy: {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
Common Mistake 3: Modifying Dictionary During Iteration
Changing a dictionary's size during iteration can cause unexpected behavior ?
data = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Wrong way - modifying during iteration
# This can skip elements or raise RuntimeError
safe_data = data.copy()
for key in safe_data:
if safe_data[key] % 2 == 0:
del data[key]
print("After removal:", data)
# Correct way - collect keys first
data2 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
keys_to_remove = [key for key, value in data2.items() if value % 2 == 0]
for key in keys_to_remove:
del data2[key]
print("Safe removal:", data2)
After removal: {'a': 1, 'c': 3}
Safe removal: {'a': 1, 'c': 3}
Common Mistake 4: Using Mutable Objects as Dictionary Keys
Dictionary keys must be immutable. Using lists or other mutable objects as keys will raise a TypeError ?
# Wrong - using mutable object as key
try:
bad_dict = {[1, 2]: 'value'} # Lists are mutable
except TypeError as e:
print(f"TypeError: {e}")
# Correct - using immutable objects as keys
good_dict = {
'string_key': 'value1',
42: 'value2',
(1, 2): 'value3' # Tuples are immutable
}
print("Valid dictionary:", good_dict)
TypeError: unhashable type: 'list'
Valid dictionary: {'string_key': 'value1', 42: 'value2', (1, 2): 'value3'}
Common Mistake 5: Not Handling Default Values Properly
Using setdefault() or defaultdict can prevent KeyError and make code cleaner ?
from collections import defaultdict
# Manual approach (verbose)
word_count = {}
text = ['apple', 'banana', 'apple', 'cherry', 'banana']
for word in text:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("Manual count:", word_count)
# Better approach using setdefault
word_count2 = {}
for word in text:
word_count2.setdefault(word, 0)
word_count2[word] += 1
print("Using setdefault:", word_count2)
# Best approach using defaultdict
word_count3 = defaultdict(int)
for word in text:
word_count3[word] += 1
print("Using defaultdict:", dict(word_count3))
Manual count: {'apple': 2, 'banana': 2, 'cherry': 1}
Using setdefault: {'apple': 2, 'banana': 2, 'cherry': 1}
Using defaultdict: {'apple': 2, 'banana': 2, 'cherry': 1}
Best Practices Summary
| Mistake | Wrong Approach | Correct Approach |
|---|---|---|
| Key Access | dict[key] |
dict.get(key, default) |
| Copying | dict2 = dict1 |
dict2 = dict1.copy() |
| Iteration | Modify during loop | Collect keys first |
| Keys | Mutable objects | Immutable objects only |
Conclusion
Avoiding these common dictionary mistakes will make your Python code more robust and prevent runtime errors. Always use get() for safe key access, create proper copies when needed, and remember that dictionary keys must be immutable objects.
