Practice Questions — Dictionaries in Python
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output of the following code?
d = {"name": "Aarav", "age": 16}
print(d["name"])
print(d["age"])Square brackets access the value associated with a key.
Aarav16Question 2
Easy
What is the output?
d = {"a": 1, "b": 2}
d["c"] = 3
print(d)
print(len(d))Assigning to a new key adds it to the dictionary.
{'a': 1, 'b': 2, 'c': 3}3Question 3
Easy
What is the output?
d = {"x": 10, "y": 20}
print(d.get("x"))
print(d.get("z"))
print(d.get("z", 0)).get() returns None for missing keys unless a default is specified.
10None0Question 4
Easy
What is the output?
d = {"a": 1, "b": 2, "c": 3}
print("a" in d)
print(1 in d)
print("d" in d)The 'in' operator checks keys, not values.
TrueFalseFalseQuestion 5
Easy
What is the output?
d = {"a": 1, "b": 2, "c": 3}
print(list(d.keys()))
print(list(d.values()))keys() returns all keys. values() returns all values.
['a', 'b', 'c'][1, 2, 3]Question 6
Easy
What is the output?
d = {"a": 1, "b": 2}
d["a"] = 10
print(d)Assigning to an existing key updates its value.
{'a': 10, 'b': 2}Question 7
Medium
What is the output?
d = {"a": 1, "b": 2, "c": 3}
val = d.pop("b")
print(val)
print(d)pop() removes the key and returns its value.
2{'a': 1, 'c': 3}Question 8
Medium
What is the output?
d = {"a": 1, "b": 2}
for key, value in d.items():
print(f"{key} -> {value}")items() returns key-value pairs as tuples, which can be unpacked.
a -> 1b -> 2Question 9
Medium
What is the output?
squares = {x: x**2 for x in range(1, 5)}
print(squares)Dictionary comprehension: {key_expr: value_expr for item in iterable}.
{1: 1, 2: 4, 3: 9, 4: 16}Question 10
Medium
What is the output?
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
merged = {**d1, **d2}
print(merged)** unpacking merges dictionaries. When keys overlap, the last one wins.
{'a': 1, 'b': 3, 'c': 4}Question 11
Medium
What is the output?
d = {}
d.setdefault("count", 0)
d["count"] += 1
d.setdefault("count", 0)
d["count"] += 1
print(d)setdefault() only sets the value if the key does not already exist.
{'count': 2}Question 12
Medium
What is the output?
school = {
"Aarav": {"marks": 90},
"Priya": {"marks": 95}
}
print(school["Priya"]["marks"])Chain keys to access nested dictionary values.
95Question 13
Hard
What is the output?
text = "abba"
count = {}
for ch in text:
count[ch] = count.get(ch, 0) + 1
print(count).get(ch, 0) returns 0 if the key does not exist, then adds 1.
{'a': 2, 'b': 2}Question 14
Hard
What is the output?
d = {"a": 1, "b": 2, "a": 3}
print(d)
print(len(d))Dictionary keys must be unique. What happens with duplicate keys in a literal?
{'a': 3, 'b': 2}2Question 15
Hard
What is the output?
d = dict.fromkeys(["a", "b", "c"], [])
d["a"].append(1)
print(d)fromkeys() with a mutable default shares the same object for all keys.
{'a': [1], 'b': [1], 'c': [1]}Question 16
Hard
What is the output?
d = {"a": 1, "b": 2, "c": 3}
filtered = {k: v for k, v in d.items() if v > 1}
print(filtered)Dictionary comprehension with a filter condition.
{'b': 2, 'c': 3}Question 17
Hard
What is the output?
d = {"x": 10, "y": 20, "z": 30}
result = max(d, key=d.get)
print(result)
print(d[result])max(dict, key=dict.get) finds the key with the highest value.
z30Mixed & Application Questions
Question 1
Easy
What is the output?
d = {"name": "Rohan"}
d["name"] = "Vikram"
print(d)Assigning to an existing key updates its value.
{'name': 'Vikram'}Question 2
Easy
What is the output?
d = {"a": 1, "b": 2}
d.clear()
print(d)
print(type(d))clear() removes all key-value pairs but the dictionary object remains.
{}<class 'dict'>Question 3
Easy
What is the output?
d = {1: "one", 2: "two", 3: "three"}
print(d[2])
print(list(d.keys()))Dictionary keys can be integers, not just strings.
two[1, 2, 3]Question 4
Medium
What is the output?
d = {"a": 1, "b": 2}
d.update({"b": 20, "c": 30})
print(d)update() adds new keys and overwrites existing ones.
{'a': 1, 'b': 20, 'c': 30}Question 5
Medium
What is the output?
d = {"a": 1, "b": 2, "c": 3}
result = d.pop("b", "not found")
result2 = d.pop("z", "not found")
print(result)
print(result2)
print(d)pop(key, default) removes and returns the value, or returns default if key is missing.
2not found{'a': 1, 'c': 3}Question 6
Medium
What is the output?
original = {"a": 1, "b": 2}
inverted = {v: k for k, v in original.items()}
print(inverted)Dictionary comprehension can swap keys and values.
{1: 'a', 2: 'b'}Question 7
Medium
What is the output?
d1 = {"a": 1}
d2 = d1
d2["b"] = 2
print(d1)
print(d1 is d2)d2 = d1 creates an alias, not a copy. Same as with lists.
{'a': 1, 'b': 2}TrueQuestion 8
Hard
What is the output?
data = [{"name": "Aarav", "marks": 90},
{"name": "Priya", "marks": 95},
{"name": "Rohan", "marks": 78}]
top = max(data, key=lambda x: x["marks"])
print(top["name"])max() with a key function can find the dict with the highest value for a specific key.
PriyaQuestion 9
Medium
What is the difference between
dict[key] and dict.get(key) when the key does not exist?One raises an error, the other returns a default value.
dict[key] raises a KeyError when the key does not exist. dict.get(key) returns None (or a custom default if specified: dict.get(key, default)) without raising an error.Question 10
Medium
Why does
in check keys and not values in a dictionary? How do you check if a value exists?Think about the purpose of dictionaries and what operation is most common.
Dictionaries are optimized for key-based access. Checking if a key exists is O(1) (constant time) because of hashing. Checking values would require O(n) linear search. Since key lookup is the primary use case,
in defaults to checking keys. To check values, use value in dict.values().Question 11
Hard
What is the output?
d = {}
for ch in "hello world":
if ch != " ":
d[ch] = d.get(ch, 0) + 1
print(d)
print(d["l"])This counts character frequency, skipping spaces.
{'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}3Question 12
Hard
What is the output?
d = {"a": [1, 2], "b": [3, 4]}
copy = d.copy()
copy["a"].append(99)
print(d)
print(copy)dict.copy() is a shallow copy. Nested mutable objects are still shared.
{'a': [1, 2, 99], 'b': [3, 4]}{'a': [1, 2, 99], 'b': [3, 4]}Multiple Choice Questions
MCQ 1
Which of the following creates an empty dictionary?
Answer: C
C is correct. Curly braces
C is correct. Curly braces
{} create an empty dictionary. [] (A) creates an empty list. () (B) creates an empty tuple. set() (D) creates an empty set (note: {} is a dict, not a set).MCQ 2
What does dict.get('key') return if 'key' does not exist?
Answer: C
C is correct.
C is correct.
.get(key) returns None when the key is not found (no error). To return a custom default, use .get(key, default). Option D describes the behavior of dict[key], not .get().MCQ 3
What does the 'in' operator check for dictionaries?
Answer: B
B is correct. The
B is correct. The
in operator checks keys by default. "name" in d checks if "name" is a key. To check values, use value in d.values().MCQ 4
Which types can be used as dictionary keys?
Answer: B
B is correct. Dictionary keys must be hashable (immutable). Strings, integers, floats, and tuples of immutables all work. Lists (C) and dictionaries cannot be keys because they are mutable.
B is correct. Dictionary keys must be hashable (immutable). Strings, integers, floats, and tuples of immutables all work. Lists (C) and dictionaries cannot be keys because they are mutable.
MCQ 5
What does d.pop('key') do?
Answer: B
B is correct.
B is correct.
pop(key) removes the key-value pair and returns the value. It raises KeyError if the key does not exist (unless a default is provided). Option D describes popitem().MCQ 6
What is the output of {x: x**2 for x in range(3)}?
Answer: B
B is correct. Dictionary comprehension creates key-value pairs. For x = 0, 1, 2: the key is x and the value is x**2. Result: {0: 0, 1: 1, 2: 4}. Option A would be a set comprehension (
B is correct. Dictionary comprehension creates key-value pairs. For x = 0, 1, 2: the key is x and the value is x**2. Result: {0: 0, 1: 1, 2: 4}. Option A would be a set comprehension (
{x**2 for x in range(3)}).MCQ 7
What happens when you add a key that already exists in a dictionary?
Answer: B
B is correct. Dictionary keys are unique. Assigning to an existing key overwrites the previous value. No error is raised, and the old value is lost.
B is correct. Dictionary keys are unique. Assigning to an existing key overwrites the previous value. No error is raised, and the old value is lost.
MCQ 8
What does d.items() return?
Answer: C
C is correct.
C is correct.
.items() returns a view object containing (key, value) tuples. It is not a regular list, but it can be iterated over and converted with list().MCQ 9
What does setdefault('key', value) do if 'key' already exists?
Answer: B
B is correct.
B is correct.
setdefault() only sets the value if the key does NOT exist. If the key already exists, it simply returns the current value without modifying anything.MCQ 10
How do you safely copy a dictionary?
Answer: B
B is correct.
B is correct.
.copy() creates a shallow copy. Option A creates an alias (not a copy). Option C gives only values (not a dict). Option D also works but is less common and readable. Note: for nested dicts, use copy.deepcopy().MCQ 11
Since which Python version are dictionaries guaranteed to maintain insertion order?
Answer: C
C is correct. In Python 3.6, CPython (the standard implementation) made dicts ordered as an implementation detail. In Python 3.7, it became part of the language specification. Before that, dictionaries were unordered.
C is correct. In Python 3.6, CPython (the standard implementation) made dicts ordered as an implementation detail. In Python 3.7, it became part of the language specification. Before that, dictionaries were unordered.
MCQ 12
What is the output of {**{'a': 1}, **{'a': 2}}?
Answer: B
B is correct. When merging with
B is correct. When merging with
** unpacking, the last value for a duplicate key wins. The second dict has 'a': 2, which overwrites the first dict's 'a': 1.MCQ 13
What does dict.copy() create?
Answer: B
B is correct.
B is correct.
.copy() creates a shallow copy: a new dict object, but nested mutable values (like lists) are still shared references. For a fully independent copy of nested structures, use copy.deepcopy().MCQ 14
What does popitem() do in Python 3.7+?
Answer: C
C is correct. In Python 3.7+,
C is correct. In Python 3.7+,
popitem() removes and returns the last inserted key-value pair (LIFO order). In older Python versions, it removed an arbitrary pair. Option D describes clear().MCQ 15
Which method merges one dictionary into another in place?
Answer: B
B is correct.
B is correct.
update() merges the given dictionary into the current one, modifying it in place. merge() (A) does not exist. extend() (C) is a list method. join() (D) is a string method.MCQ 16
What is the time complexity of checking 'key in dict'?
Answer: C
C is correct. Dictionary key lookup uses hashing, which provides O(1) average-case time complexity. This is why dictionaries are preferred over lists for lookups. List membership checking (
C is correct. Dictionary key lookup uses hashing, which provides O(1) average-case time complexity. This is why dictionaries are preferred over lists for lookups. List membership checking (
item in list) is O(n).MCQ 17
What is the output of len({'a': 1, 'b': 2, 'c': 3})?
Answer: B
B is correct.
B is correct.
len() on a dictionary returns the number of key-value pairs. This dictionary has 3 pairs, so the length is 3.MCQ 18
What does d = {}; d[(1, 2)] = 'point' do?
Answer: B
B is correct. The tuple
B is correct. The tuple
(1, 2) is used as a single dictionary key mapping to 'point'. Tuples are hashable and valid as keys. The dictionary has one entry: {(1, 2): 'point'}.Coding Challenges
Challenge 1: Word Frequency Counter
EasyGiven the string "the cat sat on the mat the cat", write a program that counts the frequency of each word and prints the result as a dictionary.
Sample Input
(No input required)
Sample Output
{'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1}
Use .split() and .get() pattern.
text = "the cat sat on the mat the cat"
words = text.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
print(freq)Challenge 2: Invert a Dictionary
EasyGiven the dictionary {'a': 1, 'b': 2, 'c': 3}, write a program that inverts it so keys become values and values become keys. Print the result.
Sample Input
(No input required)
Sample Output
{1: 'a', 2: 'b', 3: 'c'}
Use dictionary comprehension.
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
print(inverted)Challenge 3: Merge Two Dictionaries
EasyAarav has two dictionaries: d1 = {'a': 1, 'b': 2} and d2 = {'b': 3, 'c': 4}. Merge them into a new dictionary where d2's values take priority for overlapping keys.
Sample Input
(No input required)
Sample Output
{'a': 1, 'b': 3, 'c': 4}
Use ** unpacking or update().
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
merged = {**d1, **d2}
print(merged)Challenge 4: Group Students by Grade
MediumGiven a list of tuples: [('Aarav', 'A'), ('Priya', 'B'), ('Rohan', 'A'), ('Meera', 'B'), ('Vikram', 'A')], group students by their grade into a dictionary. Print the result.
Sample Input
(No input required)
Sample Output
{'A': ['Aarav', 'Rohan', 'Vikram'], 'B': ['Priya', 'Meera']}
Use setdefault() or .get() pattern.
students = [('Aarav', 'A'), ('Priya', 'B'), ('Rohan', 'A'), ('Meera', 'B'), ('Vikram', 'A')]
groups = {}
for name, grade in students:
groups.setdefault(grade, []).append(name)
print(groups)Challenge 5: Find Students Above Average
MediumGiven marks = {'Aarav': 85, 'Priya': 92, 'Rohan': 78, 'Meera': 95, 'Vikram': 88}, calculate the average marks and print only the students who scored above average.
Sample Input
(No input required)
Sample Output
Average: 87.6
Above average: {'Priya': 92, 'Meera': 95, 'Vikram': 88}
Use sum(), len(), and dictionary comprehension.
marks = {'Aarav': 85, 'Priya': 92, 'Rohan': 78, 'Meera': 95, 'Vikram': 88}
avg = sum(marks.values()) / len(marks)
print(f"Average: {avg}")
above = {name: score for name, score in marks.items() if score > avg}
print(f"Above average: {above}")Challenge 6: Nested Dictionary Access
MediumGiven a nested dictionary representing a school, write a program that prints each student's name and their total marks across all subjects.
school = {
"Aarav": {"Maths": 90, "Science": 85, "English": 88},
"Priya": {"Maths": 95, "Science": 92, "English": 91}
}Sample Input
(No input required)
Sample Output
Aarav: 263
Priya: 278
Use nested loops or sum() on values.
school = {
"Aarav": {"Maths": 90, "Science": 85, "English": 88},
"Priya": {"Maths": 95, "Science": 92, "English": 91}
}
for name, subjects in school.items():
total = sum(subjects.values())
print(f"{name}: {total}")Challenge 7: Two Lists to Dictionary
MediumGiven keys = ['name', 'age', 'city'] and values = ['Rohan', 16, 'Delhi'], write a program that creates a dictionary from these two lists using zip().
Sample Input
(No input required)
Sample Output
{'name': 'Rohan', 'age': 16, 'city': 'Delhi'}
Use zip() and dict().
keys = ['name', 'age', 'city']
values = ['Rohan', 16, 'Delhi']
result = dict(zip(keys, values))
print(result)Challenge 8: Character Frequency with Sorting
HardWrite a program that counts the frequency of each character in "programming" and prints them sorted by frequency (highest first). For ties, sort alphabetically.
Sample Input
(No input required)
Sample Output
g: 2
m: 2
r: 2
a: 1
i: 1
n: 1
o: 1
p: 1
Use .get() for counting. Use sorted() with a key.
text = "programming"
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0) + 1
sorted_chars = sorted(freq.items(), key=lambda x: (-x[1], x[0]))
for ch, count in sorted_chars:
print(f"{ch}: {count}")Challenge 9: Find Duplicate Values
HardGiven the dictionary {'a': 1, 'b': 2, 'c': 1, 'd': 3, 'e': 2}, write a program that finds and prints which values appear more than once, along with the keys that share them.
Sample Input
(No input required)
Sample Output
Value 1 is shared by: ['a', 'c']
Value 2 is shared by: ['b', 'e']
Use a dictionary to group keys by their values.
d = {'a': 1, 'b': 2, 'c': 1, 'd': 3, 'e': 2}
value_to_keys = {}
for key, value in d.items():
value_to_keys.setdefault(value, []).append(key)
for value, keys in value_to_keys.items():
if len(keys) > 1:
print(f"Value {value} is shared by: {keys}")Challenge 10: Flatten a Nested Dictionary
HardWrite a program that flattens the nested dictionary {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}} into a flat dictionary with dotted keys: {'a': 1, 'b.c': 2, 'b.d.e': 3}.
Sample Input
(No input required)
Sample Output
{'a': 1, 'b.c': 2, 'b.d.e': 3}
Use recursion or a stack-based approach.
def flatten(d, parent_key='', sep='.'):
items = {}
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, dict):
items.update(flatten(v, new_key, sep))
else:
items[new_key] = v
return items
nested = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}}
print(flatten(nested))Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn Python with a live mentor?
Explore our Python course