30 Python Dictionary MCQ for Coding Practice
Welcome to this ultimate Python Dictionary MCQ! Here, we have collected 30 questions based on dictionary in Python, which will cover basic to advanced concepts. This quiz will test your knowledge in set as well as level up your understanding in dictionary.
Whether you’re a beginner or an experienced Python programmer, this quiz is perfect for coding interviews, practices, and enhancing your knowledge in Python dictionary. So, are you ready to score 30/30? Let’s see, how well do you really understand Python dictionary? Let’s begin with question number 1.👇
1. What is a dictionary in Python?
A. A mutable, unordered collection of key-value pairs.
B. A fixed-size data structure for storing numbers.
C. A mutable and ordered collection of key-value pairs.
D. An immutable and ordered collection of key-value pairs.
c
Dictionary is an ordered collection of elements (starting from Python 3.7). It is one of the most versatile data structures for storing data in Python. It is mutable in nature, meaning that you can make changes in the existing dictionary object.
2. What is the correct way to define an empty dictionary?
A. my_dict = []
B. my_dict = ()
C. my_dict = {}
D. my_dict = “”
c
An empty dictionary is created using curly braces {}. You can also create using built-in dict() method.
3. Which of the following statements is correct about keys in a Python dictionary?
A. Keys must be unique and immutable identifiers used to access associated values.
B. Keys must be of the same data type in a single dictionary.
C. Keys can be any type of mutable object.
D. Keys can be modified after being added to the dictionary.
a
Values in the elements can be of any data type, but keys must be unique and immutable objects.
4. Which of the following is a valid key-value pair in a dictionary?
A. “name” = “Saanvi”
B. “name”: “Saanvi”
C. “name” -> “Saanvi”
D. (“name”, “Saanvi”)
b
Key-value pairs in dictionary are defined using a colon :, like “key”: value.
5. Which of the following can not be used as a dictionary key in Python?
A. “name”
B. 10
C. [1, 2, 3, 4]
D. (1, 2, 3, 4)
c
Keys must be immutable types. Tuples, strings, integers and floating-point values are immutable objects, while lists, dictionaries, and sets are mutable objects. They cannot be used as dictionary keys.
6. What will be the output of the following Python code if no error?
my_dict = {"a": 10, "b": 20, "c": 30} print(my_dict["d"])
A. 40
B. 30
C. NameError
D. KeyError
d
If you access a non-existent key in a dictionary using square brackets [], it will raise a KeyError.
7. What is the output of the following code?
my_dict = {"a": 10, "b": 20, "c": 30} print(my_dict.get("d", 40))
A. None
B. 40
C. KeyError
D. NameError
b
The get() method returns the value for the given key if it exists. If the key does not exist, it returns the None or default value provided instead of raising a KeyError. In simple words, the get() method is used to safely access a key without raising an error. Since ‘d’ is not a key in my_dict, the output is 40, which is a default value.
8. What is the output of the following code?
my_dict = {"x": 10, "y": 20} my_dict["z"] = 30 print(my_dict)
A. {‘x’: 10, ‘y’: 20}
B. {‘z’: 30}
C. {‘x’: 10, ‘y’: 20, ‘z’: 30}
D. TypeError
c
The dictionary is updated with a new key ‘z’ and value 30. So, the new dictionary has three key-value pairs.
9. Which method removes a key-value pair from a dictionary and returns its value?
A. pop()
B. popitem()
C. remove()
D. del()
a
The pop(key[, default]) method in Python removes the specified key and returns its associated value. If the key doesn’t exist, it raises a KeyError unless a default is provided.
10. What does this code output if no error present?
dict1 = {'x': 10, 'y': 20} dict2 = dict1.copy() dict2['x'] = 30 print(dict1['x'])
A. 10
B. 20
C. 30
D. KeyError
a
The dict1.copy() method creates a shallow copy of dict1. So, if you modify dict2, it does not affect dict1. Thus, dict1[‘x’] remains 10.
11. Which of the following is not a valid way to create a dictionary?
A. my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
B. my_dict = dict(a=1, b=2, c=3)
C. my_dict = {[‘a’]: 1, [‘b’]: 2, [‘c’]: 3}
D. my_dict = dict([(‘a’, 1), (‘b’, 2), (‘c’, 3)])
c
Dictionary keys must be immutable. Lists are mutable and cannot be used as keys, so this raises a TypeError.
12. What is the output of the following code?
my_dict = {'a': 1, 'b': 2, 'c': 3} print(list(my_dict.keys()))
A. [(‘a’, 1), (‘b’, 2), (‘c’, 3)]
B. [‘a’, 1, ‘b’, 2, ‘c’, 3]
C. [a, b, c]
D. [‘a’, ‘b’, ‘c’]
d
The keys() method returns a view object of the dictionary’s keys. When you pass a dictionary to list(), it returns a list of its keys. Thus, the output is [‘a’, ‘b’, ‘c’].
13. What is the result of this code?
dict1 = {'a': 1, 'b': 2, 'c': 3} dict2 = {'b': 20, 'd': 40} dict1.update(dict2) print(dict1['b'] + dict1.get('d', 30))
A. 50
B. 20
C. 60
D. 32
c
The update() is used to update an existing element in a dictionary. You can update a dictionary by adding a new element, entry, or key-value pair to an existing element. You can also merge keys and values from another dictionary into the original, overwriting existing keys if they conflict. In the above code, the update() method merges dict2 into dict1 by overwriting dict1[‘b’] from 2 to 20. It also adds dict1[‘d’] = 40 in the dict1. So, the result is dict1 = {‘a’: 1, ‘b’: 20, ‘c’: 3, ‘d’: 40}. The line dict1[‘b’] + dict1.get(‘d’, 30) gives 20 + 40 = 60.
14. What does the below program code output?
my_dict = {1: 'a', 2: 'b', 3: 'c'} print(2 in my_dict) print(4 in my_dict)
A. True True
B. True False
C. False True
D. False False
b
The in keyword checks for the existence of a key in the dictionary. Since 2 is a key, it returns True. Similarly, the key 4 is not present in the dictionary. Therefore,, it returns False.
15. Which of the following ways correctly loops through both keys and values of the dictionary and prints them as key: value pairs?
A. for key in my_dict:
B. for key, value in my_dict.keys(), my_dict.values():
C. for key, value in my_dict.items():
D. for key in my_dict.keys():
c
The items() method returns a view object containing key-value pairs. You can unpack them directly in a loop.
16. Which of the following statements will correctly add the key-value pair ‘c’: 3 to the dictionary my_dict = {‘a’: 1, ‘b’: 2}?
A. my_dict.append({‘c’: 3})
B. my_dict.update(‘c’: 3)
C. my_dict[‘c’] = 3
D. my_dict.add({‘c’: 3})
c
You can add or update a new key-value pair by assigning a value to a new key using bracket notation like dict[“key”] = value. Option B is wrong due to incorrect syntax for update(). The correct syntax is my_dict.update({‘c’: 3}).
17. What output does the Python code give if you execute?
d = {"a": 1, "b": 2} d["a"] += 1 print(d["a"])
A. 1
B. 2
C. 3
D. KeyError
b
d[“a”] += 1 increases the value from 1 to 2. So, the output is 2.
18. What will this code print?
my_dict = {1: "a", 2: "b", 3: "c", 1: "d"} print(my_dict)
A. {1: “a”, 2: “b”, 3: “c”}
B. {1: “d”, 2: “b”, 3: “c”}
C. {1: [“a”, “d”], 2: “b”, 3: “c”}
D. {1: “a”, 2: “b”, 3: “c”, 1: “d”}
b
Since the keys must be unique in the dictionary, but the key 1 is repeated in the code. Therefore, the last value “d” overwrites the first “a”.
19. What is the result of this Python code if no error present in it?
my_dict = {} my_dict[{}] = "Python" print(my_dict)
A. {{}: ‘Python’}
B. {‘{}’: ‘Python’}
C. TypeError
D. KeyError
c
Lists, sets, and dictionaries are mutable and unhashable. Therefore, you cannot use them as dictionary keys. If you try them, this raises a TypeError.
20. What does this code output?
my_dict = {"x": 1} my_dict[True] = "yes" print(my_dict)
A. {‘x’: 1, 1: ‘yes’}
B. {‘x’: 1, True: ‘yes’}
C. {True: ‘yes’}
D. {‘x’: ‘yes’}
b
In Python, True and 1 are treated as the same dictionary key because they are equal and have the same hash value.
21. What will the following code print?
my_dict = {True: "Yes", 1: "No", 1.0: "Maybe"} print(my_dict)
A. {True: “Yes”, 1: “No”, 1.0: “Maybe”}
B. {True: “Maybe”}
C. {1: “Maybe”}
D. KeyError
b
True, 1, and 1.0 are treated as the same key in Python because True == 1 == 1.0 and hash(True) == hash(1) == hash(1.0). When you insert {True: “Yes”} and then add {1: “No”}, it overwrites the same key. Again, {1.0: “Maybe”} overwrites the previous one. Thus, the dictionary ends up with just one key, and its last assigned value is {True: ‘Maybe’}.
22. If no error occurs, what will be the expected output?
my_dict = {(1, 2): "Tuple", 1: "Number"} print(my_dict[1, 2])
A. Tuple
B. Number
C. KeyError
D. SyntaxError
a
In this code, the key (1, 2) is a tuple, which is used as a single key in the dictionary like {(1, 2): “Tuple”}. The line print(my_dict[1, 2]) is exactly the same as print(my_dict[(1, 2)]). So, you’re just accessing the value for the tuple key (1, 2), which returns “Tuple” since (1, 2) is a tuple key.
23. What will be the expected output of the given Python code if you execute it?
my_dict = {(1, [2]): "Tuple", 1: "Number", 2: "String"} print(my_dict[2])
A. Tuple
B. String
C. KeyError
D. TypeError
d
You can’t use a list as part of a dictionary key because lists are mutable and unhashable.
24. Can you guess the output of the following code?
key1 = (1, 2) key2 = (1, 2) my_dict = {key1: "Hello"} print(my_dict[key2])
A. (1, 2)
B. Hello
C. KeyError
D. TypeError
b
In the above code, key1 and key2 are both tuples (1, 2), which are immutable objects and hashable. Python dictionaries allow tuples as keys because they are stable and cannot change after creation. When you access my_dict[key2], Python checks if key2 equals any existing key in the dictionary. Since key1 == key2 evaluates to True because tuples with the same elements are equal. Therefore, hash(key1) and hash(key2) produce the same hash value because the tuples are identical. The dictionary uses this hash to quickly locate the value “Hello”.
25. What will be the output of the following code?
t = (1, 2) my_dict = {t: "Python"} t += (3,) print(my_dict[t])
A. Python
B. KeyError
C. None
D. (1, 2, 3)
b
Initially, t = (1, 2), so my_dict = {(1, 2): “Python”}. Then, the line t += (3,) creates a new tuple (1, 2, 3) because it does not modify the original tuple. Tuples are immutable, so it creates a new object. Now the line print(my_dict[t]) is the same as my_dict[(1, 2, 3)]. This key does not exist, so Python raises a KeyError.
26. What does this code output?
my_dict = {'a': 1, 'b': 2} my_dict.setdefault('a', 100), my_dict.setdefault('c', 3) print(my_dict)
A. {‘a’: 1, ‘b’: 2, ‘c’: 3}
B. {‘a’: 100, ‘b’: 2, ‘c’: 3}
C. {‘a’: 100, ‘b’: 2, ‘c’: 3}
D. KeyError
a
The setdefault(key, default) method in Python returns the existing value associated with key if it already exists in the dictionary. If the key does not exist, it inserts the key with the provided default value and then returns that default. So, this method does not overwrite the value if the key is already present. Only new keys get the default value ‘c’: 3 is added.
27. What is the output of the below Python code?
my_dict = {'x': 10, 'y': 20} my_dict.update({'y': 30, 'z': 40}) print(my_dict.pop('y'), my_dict.pop('z', None))
A. 20 40
B. 30 40
C. 30 None
D. KeyError
b
The update() method modifies the key ‘y’ with associated value 30 and adds the key ‘z’ with the associated value 40. The pop(‘y’) method removes the key ‘y’ and returns the updated value 30. Similarly, the pop(‘z’, None) method returns the value 4 associated with key ‘z’. The None default is irrelevant here since the key ‘z’ exists.
28. What will the following program result on the console?
my_dict = {1: 'a', 2: 'b'} print(my_dict.fromkeys([1, 2, 3], 'x'))
A. {1: ‘a’, 2: ‘b’, 3: ‘x’}
B. {1: ‘x’, 2: ‘x’, 3: ‘x’}
C. {1: ‘a’, 2: ‘b’}
D. TypeError
b
The fromkeys(iterable, value) method in Python creates a new dictionary from a list of keys, all with the same default value. In other words, this dictionary method creates a new dictionary with the given keys and assigns them all the same default value. All keys share the same list object. Modifying one modifies them all.
29. What will the below code print on the console?
dict = {"x": [1, 2, 3]} dict["x"].append(4) print(dict)
A. {“x”: [1, 2, 3]}
B. {“x”: [4, 1, 2, 3]}
C. {“x”: [1, 2, 3, 4]}
D. KeyError
c
The line dict = {“x”: [1, 2, 3]} creates a dictionary where the key “x” points to a list: [1, 2, 3]. Next line d[“x”].append(4) modifies the list in place by adding 4 to the end of the existing list. So now, the value of “x” becomes [1, 2, 3, 4].
30. What will the expected output of the code if no error occurs in the Python code?
my_dict = {} my_dict.setdefault('a', {}).setdefault('b', []).append(1) print(my_dict.popitem())
A. (‘a’, {‘b’: [1, 1]})
B. (‘a’, {‘b’: 1})
C. (‘b’, [1])
D. (‘a’, {‘b’: [1]})
d
The line my_dict = {} creates an empty dictionary. The my_dict.setdefault(‘a’, {}) method checks if the key ‘a’ exists in my_dict. Since it doesn’t exist, it adds ‘a’: {}. The line my_dict.setdefault(‘a’, {}).setdefault(‘b’, []) builds a nested dictionary with a list. Since the key ‘b’ isn’t in it yet, it adds ‘b’: []. The .append(1) appends the value 1 to the list at my_dict[‘a’][‘b’]. Thus, my_dict becomes {‘a’: {‘b’: [1]}}. The my_dict.popitem() method removes and returns the last inserted item from my_dict. The only item is ‘a’: {‘b’: [1]}.
Quiz Results
0
Total Questions
0
Correct Answers
0
Incorrect Answers
0%
Score