Improve your Python skills by finding and fixing common mistakes in dictionary code. Practice debugging key-value operations, dictionary methods, and data manipulation with beginner-friendly exercises and solutions. Ideal for students and Python learners.
Topic: dictionaries
Fix the code that tries to create an empty dictionary but actually creates an empty set.
my_dict = {}
my_dict.add('key', 'value')
Hint: 💡 Empty curly braces create a dictionary, but 'add' is not a dictionary method.
Issue: Using 'add' method, which is not valid for dictionaries.
my_dict = {}
my_dict['key'] = 'value'
Fix the code that tries to access a non-existing key without handling the error.
my_dict = {'name': 'Alice'}
print(my_dict['age'])
Hint: 💡 What happens if the key doesn't exist?
Issue: KeyError when accessing a non-existent key.
my_dict = {'name': 'Alice'}
print(my_dict.get('age')) # Returns None if key doesn't exist
Fix the code that tries to use a list as a dictionary key.
my_dict = {[1, 2]: "value"}
Hint: 💡 Keys must be immutable types.
Issue: Lists are unhashable and cannot be used as keys.
my_dict = {(1, 2): "value"}
Fix the code that tries to delete a key that may not exist.
my_dict = {'a': 1}
del my_dict['b']
Hint: 💡 How can you safely remove a key?
Issue: KeyError if the key doesn't exist.
my_dict = {'a': 1}
my_dict.pop('b', None)
Fix the code that tries to iterate over dictionary keys incorrectly.
my_dict = {'a': 1, 'b': 2}
for key, value in my_dict:
print(key, value)
Hint: 💡 How do you get key-value pairs in a loop?
Issue: Iterating directly over dict gives keys, not key-value pairs.
my_dict = {'a': 1, 'b': 2}
for key, value in my_dict.items():
print(key, value)
Tutorials, Roadmaps, Bootcamps & Visualization Projects