Explore programming tutorials, exercises, quizzes, and solutions!
Python Dictionaries Exercises
1/20
You’re now learning about dictionaries in Python — a powerful data structure used to store information in key-value pairs. Dictionaries are highly flexible and ideal for cases where each item in a collection should be identified by a unique key, such as storing user details, configuration settings, or item lookups.
Consider the following code:
person = {"name": "Alice", "age": 30, "name": "Bob"}
print(person["name"])
What does this code demonstrate about how Python dictionaries handle duplicate keys?
In Python dictionaries, keys must be unique. If the same key is defined more than once in a dictionary literal, the last assignment overrides the earlier ones.
In this case:
person = {"name": "Alice", "age": 30, "name": "Bob"}
The second "name" key with value "Bob" replaces the earlier "Alice". Therefore, print(person["name"]) outputs:
Bob
Dictionaries do not store both values when keys are duplicated — only the latest one remains. This behavior is useful but can lead to unintentional overwriting if not handled carefully.
How can you add a new key-value pair to the dictionary?
You can add a new key-value pair to a dictionary by using the syntax d['c'] = 3. This assigns the value 3 to the key 'c' in the dictionary d.
What will be the output of the following code?
d = {'a': 1, 'b': 2}
d['a'] = 10
print(d)
When you assign a new value to an existing key in a dictionary, it updates the value for that key. In this case, d['a'] = 10 updates the value of 'a' to 10, so the resulting dictionary is {'a': 10, 'b': 2}.
Which method is used to get all the keys from a dictionary?
The keys() method is used to get all the keys from a dictionary. This will return a view object that displays a list of all keys in the dictionary.
The get() method is used to access a value for a given key. If the key does not exist, it returns a default value (in this case, 'Not Found') instead of raising an error.
What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
del d['b']
print(d)
The del statement is used to delete a specific key-value pair from the dictionary. In this case, d['b'] is deleted, and the resulting dictionary is {'a': 1, 'c': 3}.
Which of the following methods returns all the values of a dictionary?
The values() method is used to get all the values from a dictionary. It returns a view object that displays a list of all values in the dictionary.
What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
print(d.get('d', 0))
The get() method returns the default value (in this case, 0) when the specified key does not exist in the dictionary.
What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
print(d.pop('b'))
The pop() method removes the item with the specified key from the dictionary and returns the value. In this case, d.pop('b') removes the key-value pair 'b': 2, so the value 2 is returned.
Which of the following will update the value of key 'a' in the dictionary?
You can update the value of an existing key in the dictionary using the update() method or by directly assigning a new value to the key. However, Option 3 is the correct syntax for using update() to update the value of key 'a'. Option 1 directly assigns a new value to 'a'. Both methods work, but Option 3 is a standard method for updating.
What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
del d['a']
d['a'] = 10
print(d)
The dictionary initially has the key 'a'. After the del statement deletes 'a', a new value is assigned to 'a' using d['a'] = 10. This results in the dictionary {'a': 10, 'b': 2, 'c': 3}.
What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
for key, value in d.items():
if value == 2:
del d[key]
print(d)
In this code, the dictionary is being modified while iterating over it. This causes a KeyError because it is not safe to modify a dictionary while iterating over it directly. It can lead to unpredictable behavior.
Which of the following will return a new dictionary with reversed key-value pairs?
The code {v: k for k, v in d.items()} uses a dictionary comprehension to reverse the key-value pairs. This creates a new dictionary with the values as keys and the keys as values.
What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
if key == 'b':
break
print(d)
The loop breaks as soon as it encounters the key 'b', so only the key-value pair 'a': 1 remains in the dictionary. The dictionary itself is not modified, but the output shows the keys up to the break statement.
Which method can be used to merge two dictionaries?
The update() method is used to merge two dictionaries. It adds key-value pairs from the second dictionary into the first one, updating any existing keys with new values from the second dictionary.
What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
if d[key] == 2:
del d[key]
print(d)
This code attempts to delete a dictionary item while iterating over it. Modifying the dictionary during iteration can lead to a KeyError due to changes in the dictionary structure while looping.
What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
d[key] = d[key] * 2
print(d)
The loop multiplies the values in the dictionary by 2. Therefore, after iterating through the dictionary, the dictionary becomes {'a': 2, 'b': 4, 'c': 6}.
Which of the following methods allows you to check if a key exists in a dictionary without raising an error?
The 'a' in d syntax checks if the key 'a' exists in the dictionary. It returns True if the key exists and False if it does not. The has_key() method is no longer supported in Python 3, and key_exists() is not a valid method for dictionaries.
What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
new_d = d
new_d['a'] = 10
print(d)
In Python, when you assign new_d = d, both d and new_d refer to the same dictionary object. Therefore, modifying new_d will also modify d. After changing new_d['a'] = 10, both d and new_d will reflect the change.
Which of the following will return a dictionary with only the keys that have values greater than 1?
The dictionary comprehension {k: v for k, v in d.items() if v > 1} filters the dictionary to include only key-value pairs where the value is greater than 1. This returns a new dictionary with the filtered entries.
Practicing Python Dictionaries? Don’t forget to test yourself later in
our
Python Quiz.
About This Exercise: Python – Dictionaries
Welcome to the Python Dictionaries exercises — a comprehensive set of challenges designed to help you master one of the most important and versatile data structures in Python. Dictionaries store data as key-value pairs, allowing you to organize, retrieve, and manipulate information efficiently. Whether you’re a beginner or looking to deepen your understanding, these exercises will build your confidence and skills in working with dictionaries.
In this collection, you’ll explore how to create dictionaries, access and update values, add or remove key-value pairs, and iterate over dictionary elements. You’ll also learn about dictionary methods, nesting dictionaries, and how to use dictionaries for real-world data storage and retrieval tasks. Mastering dictionaries is essential for handling structured data, building configurations, and implementing complex algorithms.
These exercises cover both basic operations and advanced concepts such as dictionary comprehensions, merging dictionaries, and handling missing keys gracefully. You’ll develop problem-solving skills that translate directly to practical applications like caching, lookup tables, and data aggregation.
Whether preparing for coding interviews, academic assignments, or professional development, practicing with Python dictionaries is crucial. This topic is particularly valuable for those working in data science, web development, automation, and software engineering, where efficient data management is key.
Alongside these exercises, we encourage you to explore related Python data structures like lists, tuples, and sets to gain a holistic understanding of data organization. Be sure to reinforce your learning with our quizzes and MCQs designed to test your theoretical and practical knowledge of dictionaries.
Start practicing Python Dictionaries now to sharpen your skills in managing complex data and writing clean, efficient code. With consistent practice, you’ll gain the confidence to handle any data organization challenge that comes your way in your Python programming journey.