Let’s carefully understand the basics of Python dictionaries:
Key takeaway: Think of a dictionary like a real-life dictionary – every word (key) must be unique, and each word has exactly one meaning (value).
"age"
from the dictionary person = {"name": "Ali", "age": 25, "city": "Dhaka"}
?In Python, dictionaries store data as key-value pairs. To access values, you use the key inside square brackets or the get()
method.
person["age"]
will return 25
.person.get("age")
, not get_key()
.Correct Option: 3
Tip: When unsure whether a key exists, prefer using dict.get(key, default)
to avoid errors.
student = {"name": "Sara", "age": 20}
student["age"] = 21
student["grade"] = "A"
Let’s analyze step by step:
student = {"name": "Sara", "age": 20}
.student["age"] = 21
updates the value of "age"
to 21.student["grade"] = "A"
adds a new key-value pair.So, the final dictionary is:
{"name": "Sara", "age": 21, "grade": "A"}
Correct Option: 3
Key takeaway: Dictionaries allow updating existing keys and adding new ones dynamically.
employee = {"id": 101, "name": "Rafiq", "salary": 50000}
employee.pop("salary")
employee["department"] = "HR"
Understanding the operations step by step:
{"id": 101, "name": "Rafiq", "salary": 50000}
.employee.pop("salary")
removes the key "salary"
and its value.{"id": 101, "name": "Rafiq"}
.employee["department"] = "HR"
adds a new key-value pair."salary"
which was removed."department"
key added later.{"id": 101, "name": "Rafiq", "department": "HR"}
."id"
key.Example output:
{"id": 101, "name": "Rafiq", "department": "HR"}
Step-by-step reasoning:
Key takeaways:
pop(key)
removes a key and returns its value."city"
exists in the dictionary person = {"name": "Nadia", "age": 30, "city": "Chittagong"}
?Checking for key existence in a dictionary
"city" in person
checks whether the key exists and returns True
or False
.has_key()
was removed in Python 3.contains()
is not a valid dictionary method in Python."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:
Key takeaways:
key in dict
to safely check if a key exists.has_key()
is only in Python 2, not Python 3.get()
is true?Understanding the get()
method:
get()
does not raise a KeyError
if the key is missing. That’s the difference from accessing with square brackets.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).get()
works with any hashable key type, not just strings.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:
Key takeaways:
get()
to safely access keys without raising errors.
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
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.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.Example output:
{1: 2, 2: 2, 3: 2}
Step-by-step reasoning:
Key takeaways:
data = {"a": 10, "b": 20, "c": 30}
keys = list(data.keys())
keys.sort(reverse=True)
print(keys)
Understanding sorting of dictionary keys
data.keys()
returns a dictionary view of keys: dict_keys(['a', 'b', 'c'])
.list(data.keys())
converts it into a list: ['a', 'b', 'c']
.keys.sort(reverse=True)
sorts the list in descending order.['c', 'b', 'a']
.Example output:
['c', 'b', 'a']
Step-by-step reasoning:
Key takeaways:
sort(reverse=True)
sorts the list in descending order.inventory
by adding new_items
values?
inventory = {"apples": 5, "oranges": 3, "bananas": 2}
new_items = {"oranges": 4, "grapes": 10}
Updating dictionaries with another dictionary
update()
merges new_items
into inventory
. Existing keys (like "oranges") are updated, new keys (like "grapes") are added.add()
is not a valid dictionary method.merge()
is not a standard dictionary method in Python.Example output:
{'apples': 5, 'oranges': 4, 'bananas': 2, 'grapes': 10}
Step-by-step reasoning:
Key takeaways:
update()
is the standard way to merge dictionaries.+
or add()
do not work with dictionaries.
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
score_map
where keys are scores and values are lists of student names with that score.top_score = max(score_map.keys())
finds 92.score_map[top_score]
→ ['Rina', 'Sana']Example output:
['Rina', 'Sana']
Step-by-step reasoning:
Key takeaways:
Understanding dictionary keys and values
Example:
valid_dict = {1: "one", (2,3): "tuple key", "name": "Alice"}
# Lists cannot be keys
# invalid_dict = {[1,2]: "list key"} # Raises TypeError
Step-by-step reasoning:
Key takeaways:
TypeError: unhashable type
.
orders = [
{"id": 101, "items": ["apple", "banana"]},
{"id": 102, "items": ["banana", "orange"]},
{"id": 103, "items": ["apple", "grape", "orange"]}
]
item_count = {}
for order in orders:
for item in order["items"]:
item_count[item] = item_count.get(item, 0) + 1
most_common = [item for item, count in item_count.items() if count == max(item_count.values())]
most_common.sort()
print(most_common)
Counting items across multiple orders and finding the most common
item_count
with item frequencies.Example output:
['apple', 'banana', 'orange']
Step-by-step reasoning:
item_count
dictionary.Key takeaways:
get(key, default)
is useful for counting items.
dict1 = {"a": 2, "b": 3, "c": 5}
dict2 = {"b": 7, "c": 1, "d": 4}
Merging dictionaries by summing values of common keys
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.update()
overwrites existing keys, does not sum values.+
operator is not supported for dictionaries.Example output:
{'a': 2, 'b': 10, 'c': 6, 'd': 4}
Step-by-step reasoning:
Key takeaways:
get(key, default)
to handle missing keys safely.
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
setdefault()
to group IDs by scores in score_map
.Example output:
{50: [1, 3], 75: [2, 5]}
Step-by-step reasoning:
setdefault()
.Key takeaways:
setdefault(key, default)
is useful for grouping items without checking existence.
data = {"a": 1, "b": 2, "c": 3, "d": 4}
Rotating dictionary keys while preserving values
keys[1:] + keys[:1]
shifts keys to the left.zip()
to map rotated keys to original values and convert back to dict.reversed()
reverses order but does not rotate keys.Example output:
{'b': 1, 'c': 2, 'd': 3, 'a': 4}
Step-by-step reasoning:
Key takeaways:
zip()
is useful for remapping keys to values.Understanding dictionary comprehensions
if
statements.if
conditions.Example:
# Squares of even numbers from 1 to 5
squares = {x: x**2 for x in range(1,6) if x % 2 == 0}
print(squares) # Output: {2: 4, 4: 16}
Step-by-step reasoning:
if x % 2 == 0
).x: x**2
.Key takeaways:
data = [
{"name": "Alice", "grades": [85, 90, 95]},
{"name": "Bob", "grades": [75, 80]},
{"name": "Charlie", "grades": [100]},
]
avg_grade = {student["name"]: sum(student["grades"])/len(student["grades"]) for student in data}
top_students = {name: avg for name, avg in avg_grade.items() if avg >= 90}
print(top_students)
Calculating average grades and filtering with dictionary comprehension
Example output:
{'Alice': 90.0, 'Charlie': 100.0}
Step-by-step reasoning:
avg_grade
: {'Alice': 90.0, 'Bob': 77.5, 'Charlie': 100.0}Key takeaways:
data = {"x": 1, "y": 2, "z": 1, "w": 3}
Inverting a dictionary with grouping for duplicate values
setdefault()
to create a list for each value, appending all keys with that value.zip()
only maps first occurrence → duplicates are lost.Example output:
{1: ['x', 'z'], 2: ['y'], 3: ['w']}
Step-by-step reasoning:
inverted
dictionary.Key takeaways:
setdefault()
is powerful for grouping values when inverting dictionaries.Understanding nested dictionaries
data['outer']['inner']
, and modify them.Example:
data = {"student1": {"score": 85, "grade": "B"}}
data["student1"]["score"] = 90
print(data) # Output: {'student1': {'score': 90, 'grade': 'B'}}
Step-by-step reasoning:
data['student1']
.data['student1']['score']
.data['student1']['score'] = 90
.Key takeaways:
inventory = {
"fruits": {"apple": 10, "banana": 5},
"vegetables": {"carrot": 7, "spinach": 3}
}
for category, items in inventory.items():
for item in items:
items[item] += 2
total_count = {category: sum(items.values()) for category, items in inventory.items()}
print(total_count)
Updating nested dictionary values and calculating totals
Example output:
{'fruits': 19, 'vegetables': 14}
Step-by-step reasoning:
Key takeaways:
Practicing Python Dictionaries? Don’t forget to test yourself later in our Python Quiz.
Dictionaries are one of the most important and flexible data structures in Python, and at Solviyo we make sure you get comfortable with them through a mix of hands-on Python exercises and interactive Python MCQs. A dictionary in Python stores data as key-value pairs, making it perfect for scenarios where fast lookups, efficient updates, and clear mappings are required. From storing user profiles to handling configurations, dictionaries are everywhere in real-world Python programming.
We start with the fundamentals. Our Python dictionary exercises guide you step by step in creating dictionaries, accessing values using keys, updating entries, and removing items. Alongside these exercises, you’ll find Python MCQs that test your understanding of how dictionaries work, ensuring you not only learn the syntax but also the logic behind them. This balance of exercises and MCQs gives you both confidence and clarity.
Once the basics are clear, we move into more advanced Python dictionary concepts. You’ll practice iterating through keys and values, using dictionary methods like get()
, items()
, and update()
, and even explore dictionary comprehensions for concise data manipulation. These topics are reinforced with Python MCQs that focus on real interview-style questions, helping you avoid common mistakes and build strong problem-solving skills.
We also dive into practical, real-world applications. Our dictionary exercises cover scenarios like counting word frequencies, grouping data, or mapping IDs to values. By solving these problems, you’ll see how dictionaries can make Python code faster, cleaner, and more efficient. The included MCQs push you to think critically and prepare for coding interviews, academic exams, or professional development tasks where Python dictionaries play a key role.
At Solviyo, we believe learning should be simple and interactive. That’s why each exercise is paired with an explanation, and each MCQ is designed to clarify tricky concepts that many learners struggle with. By the end of this section, you’ll be able to confidently create, modify, and optimize Python dictionaries for a wide range of applications.
Start practicing Python dictionaries today with Solviyo’s exercises and MCQs. With consistent practice, you’ll not only master this essential data structure but also sharpen your overall Python programming skills for real-world success.