Playing as a guest? to earn XP and track your progress.
๐ Dictionaries Quiz
๐ Dictionaries
What is a dictionary in Python?
A list of strings only
A sequence of characters
An ordered, immutable sequence
A mutable collection of key : value pairs in { }
A dictionary maps each key to a value, and values are looked up by key rather than by index.
For student = {"roll": 101, "name": "Riya", "marks": 92.5}, what does student["name"] return?
'name'
'Riya'
101
KeyError
The key "name" is mapped to the value "Riya".
In the analogy of an English dictionary, the 'word' you look up corresponds to the:
Index
Length
Key
Value
You look up a word (key) to find its meaning (value).
For d = {"a": 1, "b": 2}, what does d[0] do?
Looks for a key 0, and raises KeyError since there is none
Returns ('a', 1)
Returns 1 (the first item)
Returns None
There is no positional index in a dictionary; d[0] looks for the KEY 0.
What is type({})?
<class 'tuple'>
<class 'set'>
<class 'list'>
<class 'dict'>
{} creates an empty dictionary.
What is emp after emp = dict(name="Aman", age=30)?
{name: 'Aman', age: 30}
{'name': 'Aman', 'age': 30}
Error
['Aman', 30]
With keyword arguments, dict() makes the argument names into string keys.
What is dict([(1, "one"), (2, "two")])?
Error
[(1, 'one'), (2, 'two')]
{1: 'one', 2: 'two'}
{'one': 1, 'two': 2}
dict() can build a dictionary from a list of (key, value) pairs.
What does dict.fromkeys(["Riya", "Aman"], 0) return?
{'Riya': 0, 'Aman': 0}
{'Riya': None, 'Aman': None}
{0: 'Riya', 0: 'Aman'}
['Riya', 'Aman', 0]
fromkeys() creates a dictionary with the given keys, all set to the same value.
What does dict.fromkeys([1, 2, 3]) return?
{1: 0, 2: 0, 3: 0}
Error
{}
{1: None, 2: None, 3: None}
When no value is given, fromkeys() uses None.
What is printed after d = {"a": 1, "b": 2, "a": 3} and print(d)?
{'a': 1, 'b': 2}
{'a': 3, 'b': 2}
Error
{'a': 1, 'b': 2, 'a': 3}
Keys must be unique, so for a repeated key the last value wins.
Which of these can be used as a dictionary key?
A list of strings
{"a": 1}
(2, 3)
[1, 2]
Keys must be immutable; a tuple of immutable values is allowed, but lists and dictionaries are not.
What happens with bad = {[1, 2]: "list key"}?
TypeError: unhashable type: 'list'
It works
ValueError
KeyError
A list is mutable, so it cannot be a dictionary key.
Which statement about dictionary values is correct?
They must be unique
They must be immutable
They must be strings
They can be of any type, and duplicates are allowed
Only keys have restrictions (unique and immutable); values can be anything.
For student = {"roll": 101, "name": "Riya"}, what does student["age"] give?
None
KeyError: 'age'
''
0
Square-bracket access raises a KeyError when the key is missing.
For student = {"roll": 101, "name": "Riya"}, what does student.get("age") return?
'age'
KeyError
None
0
get() returns None for a missing key instead of raising an error.
What does student.get("age", "N/A") return if the key "age" is missing?
'N/A'
KeyError
'age'
None
The second argument of get() is the default value returned for a missing key.
Which statement comparing d[key] and d.get(key) is correct?
They are identical in every way
Both raise KeyError for a missing key
d.get(key) can be used to add items
d[key] raises KeyError for a missing key; d.get(key) returns None (or a default)
Both return the value for an existing key; only d[key] = value can add or update an item.
For student = {"roll": 101, "name": "Riya"}, what is "Riya" in student?
KeyError
False
None
True
in checks KEYS only; "Riya" is a value. Use "Riya" in student.values() to check values.
What is stock after this code?
stock = {"pen": 50, "pencil": 30} stock["pen"] = 45 stock["eraser"] = 20
KeyError
{'pen': 50, 'pencil': 30, 'eraser': 20}
{'pen': 45, 'pencil': 30, 'eraser': 20}
{'pen': 45, 'eraser': 20}
d[key] = value updates an existing key and adds a new one.
For d = {"a": 1, "b": 2, "c": 3}, what is d after del d["b"]?
{'a': 1, 'c': 3}
{'a': 1, 'b': 2}
{'b': 2}
Error
del d[key] removes the item with that key.
For d = {"a": 1, "b": 2, "c": 3}, what does x = d.pop("a") store in x?
None
('a', 1)
'a'
1
pop(key) removes the item and returns its VALUE.
For d = {"a": 1, "b": 2}, what does d.pop("z", 0) return?
'z'
0
KeyError
None
With a default, pop() returns it instead of raising an error; d is unchanged.
For d = {"a": 1, "b": 2, "c": 3}, what does d.popitem() return?
('a', 1)
3
('c', 3)
A random item
popitem() removes and returns the LAST inserted item as a (key, value) tuple.
Which statement comparing pop() and popitem() is correct?
pop(key) removes the given key and returns its value; popitem() removes the last inserted item and returns a (key, value) tuple
popitem() needs a key
pop() takes no argument
Both return tuples
pop needs a key and returns a value; popitem takes no argument and returns a tuple.
When you loop with 'for x in d:' over a dictionary d, x takes:
The values
(key, value) tuples
The indices
The keys
A for loop over a dictionary gives its keys one by one.
Which loop gives both the key and the value on each iteration?
for k in d.keys():
for k, v in d.items():
for k in d:
for v in d.values():
items() gives (key, value) pairs that can be unpacked in the loop.
What is the total after this code?
marks = {"Maths": 95, "Physics": 88, "Chemistry": 91} total = 0 for m in marks.values(): total += m
MathsPhysicsChemistry
3
274
Error
values() gives 95, 88 and 91, which add up to 274.
For d = {"x": 10, "y": 20}, what is list(d.items())?
[('x', 10), ('y', 20)]
{'x': 10, 'y': 20}
['x', 'y']
[10, 20]
items() gives the (key, value) pairs; list() turns the view object into a list.
What do keys(), values() and items() return?
Lists
Strings
Tuples
Special view objects (wrap them in list() to get a list)
They return view objects such as dict_keys(['x', 'y']).
What does len({"a": 1, "b": 2}) return?
3
2
4
1
len() counts the items (key-value pairs), not keys and values separately.
What is the output of print(len({"a": 1, "b": 2, "a": 3}))?
3
Error
2
1
The duplicate key "a" is stored only once.
What is d after this code?
d = {"a": 1, "b": 2} d.update({"b": 9, "c": 3})
{'a': 1, 'b': 9, 'c': 3}
Error
{'a': 1, 'b': 2, 'c': 3}
{'b': 9, 'c': 3}
update() adds the new items and overwrites the values of keys that are already present.
What does {"a": 1}.setdefault("b", 5) do?
Raises KeyError
Returns None
Returns 1
Returns 5 and adds 'b': 5
If the key is absent, setdefault() adds k : v and returns v; if present, it returns the existing value.
For prices = {"apple": 120, "banana": 40, "mango": 90}, what does max(prices) return?
120
'mango'
'apple'
90
max() works on the KEYS by default; 'mango' is the largest alphabetically. Use max(prices.values()) for the largest value.
What does sorted({"b": 2, "c": 1, "a": 3}) return?
[('a', 3), ('b', 2), ('c', 1)]
[1, 2, 3]
['a', 'b', 'c']
{'a': 3, 'b': 2, 'c': 1}
sorted() on a dictionary returns a sorted list of its KEYS.
What is printed after this code?
A = {"x": 1} B = A B["y"] = 2 print(A)
{'x': 1, 'y': 2}
{'x': 1}
Error
{'y': 2}
B = A is an alias, so changes through B also appear in A. Use A.copy() for an independent copy.
For students = {101: {"name": "Riya"}, 102: {"name": "Aman"}}, what is students[102]["name"]?
102
KeyError
'Riya'
'Aman'
students[102] is the inner dictionary, and ['name'] gets 'Aman' from it.
Which statement comparing a list and a dictionary is correct?
Both use { }
A list is accessed by integer index; a dictionary by keys
A list is accessed by key; a dictionary by index
In a dictionary, in checks values
A list stores values in [ ] by position; a dictionary stores key : value pairs in { } and in checks keys.
What does the character-frequency program print for 'banana'?
{'b': 1, 'a': 1, 'n': 1}
{'a': 3, 'n': 2}
{'b': 1, 'a': 3, 'n': 2}
{'banana': 1}
Each character's count is stored with the character as the key.
In freq[ch] = freq.get(ch, 0) + 1, what does freq.get(ch, 0) return for a character seen for the first time?
0
1
KeyError
None
get() returns 0 for a missing key, so the count starts at 0 + 1 = 1.
What does the frequency program (using get()) print for "mississippi"?
{'i': 4, 's': 4}
{'m': 1, 'i': 3, 's': 4, 'p': 2}
{'m': 1, 'i': 4, 's': 3, 'p': 2}
{'m': 1, 'i': 4, 's': 4, 'p': 2}
m occurs once, i four times, s four times and p twice.
In the word-frequency program for "the cat and the hat and the bat", what is the count of 'the'?
1
3
2
4
The sentence is split into words, and 'the' appears 3 times.
In the topper program, what is printed for {"Riya": 92, "Aman": 85, "Zoya": 97, "Kabir": 88}?
Topper: Riya with 92 marks
Topper: Kabir with 88 marks
Topper: Zoya with 97 marks
Topper: Aman with 85 marks
The loop keeps track of the highest marks; 97 (Zoya) is the maximum.
What does the invert-dictionary program produce from {"IN": "India", "JP": "Japan"}?
{'India': 'IN', 'Japan': 'JP'}
Error
[('India', 'IN')]
{'IN': 'India', 'JP': 'Japan'}
It swaps keys and values: code_of[country] = code.
What is printed after this code?
d = {1: "one", 2: "two", 3: "three"} d[2] = "TWO" d[4] = "four" print(d.get(5, "not found"), len(d))
KeyError
not found 3
None 4
not found 4
Key 5 is missing, so the default is returned; the dictionary now has 4 items.
What is printed after this code?
stock = {"pen": 10, "ink": 5, "pad": 8} x = stock.pop("ink") y = stock.popitem() print(x, y)
('ink', 5) 8
5 ('pad', 8)
5 ('pen', 10)
ink pad
pop('ink') returns 5; popitem() removes the last inserted item, ('pad', 8).
Following on, stock is now {"pen": 10}. What is stock after stock.update({"pen": 12, "clip": 20})?
{'pen': 10, 'clip': 20}
{'clip': 20}
{'pen': 12, 'clip': 20}
{'pen': 22, 'clip': 20}
update() overwrites 'pen' with 12 and adds 'clip'.
What does d become after this code?
word = "APPLE" d = {} for ch in word: d[ch] = d.get(ch, 0) + 1
{'A': 1, 'P': 2, 'L': 1, 'E': 1}
{'A': 1, 'P': 1, 'L': 1, 'E': 1}
{'APPLE': 1}
{'P': 2}
P appears twice; every other letter appears once.
For d = {'A': 1, 'P': 2, 'L': 1, 'E': 1}, what does print("P" in d, 2 in d, 2 in d.values()) display?
False False True
True False False
True True True
True False True
'P' is a key; 2 is not a key, but it is one of the values.
What does {"x": 1, "x": 2} evaluate to?
{'x': 1}
{'x': 2}
{'x': 1, 'x': 2}
Error
For a duplicate key, the last value overwrites the earlier one.
What does len({}) return?
Error
None
0
1
An empty dictionary has 0 items.
Why can a tuple be a dictionary key but a list cannot?
Keys must be immutable; a tuple (of immutable values) is immutable, but a list is mutable
Tuples use round brackets
Lists are too long
Tuples are faster
Mutable objects such as lists are unhashable and cannot be keys.