After adding department: {"id": 101, "name": "Rafiq", "department": "HR"}
Key takeaways:
pop(key) removes a key and returns its value.
You can add new key-value pairs by direct assignment.
Dictionaries are mutable, so changes happen in place.
Which of the following correctly checks if the key "city" exists in the dictionary person = {"name": "Nadia", "age": 30, "city": "Chittagong"}?
Checking for key existence in a dictionary
Option 1 – Correct: "city" in person checks whether the key exists and returns True or False.
Option 2 – Incorrect: has_key() was removed in Python 3.
Option 3 – Incorrect: contains() is not a valid dictionary method in Python.
Option 4 – Incorrect: "city" in person.values() checks values, not keys.
Example:
person = {"name": "Nadia", "age": 30, "city": "Chittagong"}
print("city" in person) # Output: True
Step-by-step reasoning:
Look at the dictionary keys: "name", "age", "city".
Check if "city" is present among keys → True.
Key takeaways:
Use key in dict to safely check if a key exists.
Do not confuse keys and values when checking existence.
Remember that has_key() is only in Python 2, not Python 3.
Which of the following statements about the Python dictionary method get() is true?
Understanding the get() method:
Option 1 – Incorrect: get() does not raise a KeyError if the key is missing. That’s the difference from accessing with square brackets.
Option 2 – Correct: get(key, default) returns the value for the key if it exists; otherwise, it returns the default value (or None if default is not provided).
Option 3 – Incorrect: get() works with any hashable key type, not just strings.
Option 4 – Incorrect: get() does not remove the key from the dictionary.
Example:
person = {"name": "Rina", "age": 28}
print(person.get("age")) # Output: 28
print(person.get("city", "NA")) # Output: NA
Step-by-step reasoning:
Check if key "age" exists → Yes → returns 28.
Check if key "city" exists → No → returns default "NA".
Key takeaways:
Use get() to safely access keys without raising errors.
You can provide a default value to handle missing keys gracefully.
This is especially useful when working with dynamic or user-generated data.
What is the output after execution of following code snippet?
numbers = [1, 2, 3, 2, 1, 4, 5, 3]
frequency = {num: numbers.count(num) for num in numbers}
filtered = {k: v for k, v in frequency.items() if v > 1}
print(filtered)
Understanding dictionary comprehension and filtering
Step 1 – frequency = {num: numbers.count(num) for num in numbers} This creates a dictionary where each number in the list is a key and its value is the count of occurrences.
Step 2 – filtered = {k: v for k, v in frequency.items() if v > 1} This filters the dictionary to include only numbers that appear more than once.
Option 1 – Incorrect: Shows all counts as 1, which is not true.
Option 2 – Incorrect: Count for 1 is correct (2 in filtered), 4 and 5 should be excluded.
Option 3 – Incorrect: Counts for 4 and 5 are wrong (should be excluded).
Option 4 – Correct: Only numbers appearing more than once are included → {1: 2, 2: 2, 3: 2}
Example output:
{1: 2, 2: 2, 3: 2}
Step-by-step reasoning:
Count occurrences: {1: 2, 2: 2, 3: 2, 4: 1, 5: 1}
Filter by v > 1 → {1: 2, 2: 2, 3: 2}
Key takeaways:
Use dictionary comprehension for quick transformations.
Filtering dictionaries with conditions helps extract only relevant data.
This pattern is useful for counting frequencies and identifying duplicates.
What is the output after execution of the following code snippet?
Start with inventory: {'apples': 5, 'oranges': 3, 'bananas': 2}
Update with new_items → 'oranges' value changes to 4, 'grapes' is added
Final inventory: {'apples': 5, 'oranges': 4, 'bananas': 2, 'grapes': 10}
Key takeaways:
update() is the standard way to merge dictionaries.
Existing keys are overwritten, new keys are added.
Other methods like + or add() do not work with dictionaries.
What is the output after execution of the following code snippet?
students = [
{"name": "Amin", "score": 85},
{"name": "Rina", "score": 92},
{"name": "Tariq", "score": 75},
{"name": "Sana", "score": 92}
]
# Create a dictionary mapping scores to list of student names
score_map = {}
for student in students:
score = student["score"]
name = student["name"]
if score in score_map:
score_map[score].append(name)
else:
score_map[score] = [name]
# Print students with top score
top_score = max(score_map.keys())
print(score_map[top_score])
Mapping scores to students using a dictionary
The code creates a dictionary score_map where keys are scores and values are lists of student names with that score.
Merging dictionaries by summing values of common keys
Option 1 – Correct: Uses a dictionary comprehension with set(dict1) | set(dict2) to get all keys. dict1.get(k,0) + dict2.get(k,0) sums values for keys present in both dictionaries and keeps others as-is.
Option 2 – Incorrect: update() overwrites existing keys, does not sum values.
Option 3 – Incorrect: + operator is not supported for dictionaries.
Option 4 – Incorrect: Only iterates dict1 keys → misses key 'd' from dict2.
Use get(key, default) to handle missing keys safely.
This pattern is useful when combining counts or measurements from multiple datasets.
What is the output after execution of the following code snippet?
records = [
{"id": 1, "score": 50},
{"id": 2, "score": 75},
{"id": 3, "score": 50},
{"id": 4, "score": 90},
{"id": 5, "score": 75}
]
# Group IDs by scores
score_map = {}
for record in records:
score_map.setdefault(record["score"], []).append(record["id"])
# Find scores with exactly 2 students
result = {score: ids for score, ids in score_map.items() if l_
Grouping dictionary values and filtering by length
The code uses setdefault() to group IDs by scores in score_map.
Step 1 – Build score_map:
50 → [1, 3]
75 → [2, 5]
90 → [4]
Step 2 – Filter scores with exactly 2 students:
50 → 2 students → included
75 → 2 students → included
90 → 1 student → excluded
Final result: {50: [1, 3], 75: [2, 5]}
Option 1 – Correct: Matches the filtered result.
Option 2 – Incorrect: Includes 90 which has only 1 student.
Option 3 – Incorrect: Includes 90 and misses 50 → wrong.
Option 4 – Incorrect: Includes all scores → 90 should be excluded.
Example output:
{50: [1, 3], 75: [2, 5]}
Step-by-step reasoning:
Create empty score_map.
Iterate through records and append IDs to the corresponding score key using setdefault().
Filter dictionary: only include entries where the list length is exactly 2.
Result → {50: [1, 3], 75: [2, 5]}.
Key takeaways:
setdefault(key, default) is useful for grouping items without checking existence.
Dictionary comprehensions allow filtering based on complex conditions like list length.
This technique is handy for analyzing grouped data or identifying patterns in records.
Which option correctly rotates dictionary keys by one position while preserving the values?
data = {"a": 1, "b": 2, "c": 3, "d": 4}
Rotating dictionary keys while preserving values
Option 1 – Correct:
Extract keys and values as lists.
Rotate keys by one: keys[1:] + keys[:1] shifts keys to the left.
Use zip() to map rotated keys to original values and convert back to dict.
Option 2 – Incorrect: reversed() reverses order but does not rotate keys.
Option 3 – Incorrect: Rotates items as (key, value) pairs → preserves original key-value mapping, not rotation of keys.
Option 4 – Incorrect: Does not rotate keys, just copies the dictionary.
Nested loops can efficiently update values in nested dictionaries.
Dictionary comprehensions allow summarizing data concisely.
This pattern is useful for inventory management, aggregation, or reporting tasks.
Quick Recap of Python Dictionaries Concepts
If you are not clear on the concepts of Dictionaries, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.
What Is a Python Dictionary
A Python dictionary is a collection of key-value pairs, where each key is unique and immutable (e.g., string, number, tuple) and maps to a value, which can be of any data type. Dictionaries let you store and retrieve data efficiently using the key. Since Python 3.7, dictionaries maintain insertion order.
Creating Python Dictionaries
You can create a dictionary using curly braces {}, the dict() constructor, or from iterables of key-value pairs:
You can access dictionary values using keys or the get() method for safe retrieval:
settings = {"theme": "dark", "font_size": 14, "show_line_numbers": True}
print(settings["theme"]) # dark
print(settings.get("font_size")) # 14
# Safe retrieval using get() to avoid KeyError
print(settings.get("auto_save", False)) # returns False if key not found
Adding, Updating, and Removing Items
Dictionaries are mutable: you can add new key-value pairs, update existing ones, or remove entries.
data = {"id": 101, "name": "Samir"}
# Add new key-value
data["role"] = "editor"
# Update existing value
data["name"] = "Samir Ahmed"
# Remove by key
del data["id"]
# Remove and return value
age = data.pop("age", None)
# Clear the dictionary
data.clear()
Built-in Dictionary Methods & Operations
Python dictionaries provide many useful methods for data access, modification, and iteration:
Method / Function
Description
keys()
Returns a view of all keys
values()
Returns a view of all values
items()
Returns a view of (key, value) pairs
get(key, default)
Retrieves value for key; returns default if key not found
pop(key[, default])
Removes key and returns its value (or default if key absent)
popitem()
Removes last inserted key-value pair
clear()
Removes all items from the dictionary
copy()
Returns a shallow copy of the dictionary
fromkeys(seq, default=None)
Creates a new dict with keys from seq, each assigned default
dict comprehension
Create dict dynamically: {x: x*x for x in range(1,6)}
Iterating Over a Dictionary
You can iterate over keys, values, or key-value pairs:
user = {"username": "maya", "score": 85, "level": 3}
# Looping keys
for key in user.keys():
print(key)
# Looping values
for value in user.values():
print(value)
# Looping key-value pairs
for key, value in user.items():
print(key, ":", value)
Nested Dictionaries & Using Complex Data
Dictionaries can contain other dictionaries or lists, useful for structured data:
Practicing Python Dictionaries? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python Dictionaries Exercises
Welcome to Solviyo’s Python Dictionaries exercises, designed to help you master one of Python’s most flexible and powerful data structures. Dictionaries store data as key-value pairs, enabling fast lookups, efficient updates, and clear mappings. These exercises provide hands-on practice and interactive MCQs to ensure you understand both syntax and practical usage.
What You Will Learn
In this set of Python Dictionaries exercises, you will explore:
Creating dictionaries and accessing values using keys.
Adding, updating, and removing dictionary entries.
Iterating through dictionaries using keys, values, and items.
Using built-in methods like get(), items(), update(), and dictionary comprehensions.
Applying dictionaries to real-world problems such as counting word frequencies, mapping IDs to values, and grouping data.
Reinforcing learning with interactive MCQs to understand common pitfalls and interview-style questions.
Writing clean, efficient, and optimized dictionary code for practical Python applications.
Why Learning Python Dictionaries Matters
Dictionaries are a fundamental part of Python programming. Mastering them allows you to efficiently store and retrieve data, write concise and maintainable code, and solve real-world problems effectively. Understanding dictionaries prepares you for advanced topics, coding interviews, and professional Python development.
Start Practicing Python Dictionaries Today
By completing these exercises, you will gain confidence in using Python dictionaries for a wide range of tasks. Each exercise includes detailed explanations to reinforce learning and help you apply concepts correctly. Start practicing Python Dictionaries exercises now, and build a strong foundation in Python data structures for real-world programming success.
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.