Python Questions and Answers – Dictionary – 4

This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Dictionary – 4”.

1. The following Python code is invalid.

class demo(dict):
  def __test__(self,key):
    return []
a = demo()
a['test'] = 7
print(a)

a) True
b) False
View Answer

Answer: b
Explanation: The code runs successfully and prints {‘test’: 7}, so it is valid Python code. It defines a class inheriting from dict, adds an unused method __test__, sets a key ‘test’, and prints the dictionary. There is no syntax or runtime error. Therefore, the code is not invalid, and the correct answer is False.
advertisement

2. What will be the output of the following Python code?

count={}
count[(1,2,4)] = 5
count[(4,2,1)] = 7
count[(1,2)] = 6
count[(4,2,1)] = 2
tot = 0
for i in count:
    tot=tot+count[i]
print(len(count)+tot)

a) 25
b) 17
c) 16
d) Tuples can’t be made keys of a dictionary
View Answer

Answer: c
Explanation: The dictionary uses tuples as keys, which is valid since tuples are immutable. The key (4,2,1) is assigned twice, so the second value (2) overwrites the first (7). The final dictionary has 3 keys, and the sum of the values is 5 + 2 + 6 = 13. Thus, the output is 3 + 13 = 16, so the correct answer is 16.
Free 30-Day Python Certification Bootcamp is Live. Join Now!

3. What will be the output of the following Python code?

a={}
a[2]=1
a[1]=[2,3,4]
print(a[1][1])

a) [2,3,4]
b) 3
c) 2
d) An exception is thrown
View Answer

Answer: b
Explanation: The dictionary a stores an integer under key 2 and a list under key 1. The expression a[1][1] first retrieves the list [2, 3, 4], then accesses its second element, which is 3. Hence, the output is 3.
advertisement

4. What will be the output of the following Python code?

a={'B':5,'A':9,'C':7}
print(sorted(a))

a) [‘A’, ’B’, ’C’]
b) [‘B’, ’C’, ’A’]
c) [5, 7, 9]
d) [9, 5, 7]
View Answer

Answer: a
Explanation: The sorted() function sorts the dictionary keys in ascending (alphabetical) order. Since the keys are ‘B’, ‘A’, and ‘C’, sorting them gives [‘A’, ‘B’, ‘C’].

5. What will be the output of the following Python code?

a={i: i*i for i in range(6)}
print(a)

a) Dictionary comprehension doesn’t exist
b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}
c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25}
d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
View Answer

Answer: d
Explanation: This is a dictionary comprehension that generates a dictionary where each key i is mapped to its square i*i for i in range(6), i.e., 0 to 5. So the output is: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

6. What will be the output of the following Python code?

a={}
print(a.fromkeys([1,2,3],"check"))

a) Syntax error
b) {1: ‘check’, 2: ‘check’, 3: ‘check’}
c) “check”
d) {1:None,2:None,3:None}
View Answer

Answer: b
Explanation: The fromkeys() method creates a new dictionary with the specified keys and assigns each key the same value. Here, keys [1, 2, 3] are all given the value “check”. So the output is {1: ‘check’, 2: ‘check’, 3: ‘check’}.

7. What will be the output of the following Python code?

b={}
print(all(b))

a) { }
b) False
c) True
d) An exception is thrown
View Answer

Answer: c
Explanation: The all() function returns True when called on an empty iterable, as there are no false elements to contradict it. Since b is an empty dictionary, all(b) returns True. Hence, the output is True.

8. If b is a dictionary, what does any(b) do?
a) Returns True if any key of the dictionary is true
b) Returns False if any key of the dictionary is false
c) Returns True if all keys of the dictionary are true
d) Method any() doesn’t exist for dictionary
View Answer

Answer: a
Explanation: The any() function returns True if any element of the iterable is True. When used on a dictionary, it checks the keys (not the values). So any(b) returns True if at least one key is truthy (e.g., not 0, not False, not empty string).

Example:

b = {0: 'x', 1: 'y'}
any(b)True  (because key 1 is truthy)

9. What will be the output of the following Python code?

a={"a":1,"b":2,"c":3}
b=dict(zip(a.values(),a.keys()))
print(b)

a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
b) An exception is thrown
c) {‘a’: ‘b’: ‘c’: }
d) {1: ‘a’, 2: ‘b’, 3: ‘c’}
View Answer

Answer: d
Explanation: The zip(a.values(), a.keys()) pairs each value with its corresponding key, effectively reversing the dictionary’s key-value order. Using dict() on this zipped object creates a new dictionary with values as keys and keys as values. So, the output is {1: ‘a’, 2: ‘b’, 3: ‘c’}.

10. What will be the output of the following Python code?

a={i: 'A' + str(i) for i in range(5)}
print(a)

a) An exception is thrown
b) {0: ‘A0’, 1: ‘A1’, 2: ‘A2’, 3: ‘A3’, 4: ‘A4’}
c) {0: ‘A’, 1: ‘A’, 2: ‘A’, 3: ‘A’, 4: ‘A’}
d) {0: ‘0’, 1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’}
View Answer

Answer: b
Explanation: The dictionary comprehension creates keys from 0 to 4 and assigns each key a value formed by concatenating ‘A’ with the string of the key. This results in {0: ‘A0’, 1: ‘A1’, 2: ‘A2’, 3: ‘A3’, 4: ‘A4’}.

11. What will be the output of the following Python code?

a=dict()
print(a[1])

a) An exception is thrown since the dictionary is empty
b) ‘ ‘
c) 1
d) 0
View Answer

Answer: a
Explanation: The dictionary a is empty and does not contain the key 1. Attempting to access a non-existent key using square brackets (a[1]) raises a KeyError in Python. To avoid this, the get() method can be used instead, which returns None or a default value if the key is missing.

12. What will be the output of the following Python code?

import collections
a=dict()
a=collections.defaultdict(int)
print(a[1])

a) 1
b) 0
c) An exception is thrown
d) ‘ ‘
View Answer

Answer: b
Explanation: The code uses collections.defaultdict with int as the default factory function. When a[1] is accessed and the key 1 doesn’t exist, defaultdict automatically creates it with a default value of int(), which is 0. So the output is 0, and no exception is raised.

13. What will be the output of the following Python code?

import collections
a=dict()
a=collections.defaultdict(str)
print(a['A'])

a) An exception is thrown since the dictionary is empty
b) ‘ ‘
c) ‘A’
d) 0
View Answer

Answer: b
Explanation: The collections.defaultdict(str) creates a dictionary that returns a default value when a missing key is accessed. Since the default factory is str, which returns an empty string (”), accessing a missing key like ‘A’ doesn’t raise an error—it simply returns ”. Therefore, the output is an empty string.

14. What will be the output of the following Python code?

import collections
b=dict()
b=collections.defaultdict(lambda: 7)
print(b[4])

a) 4
b) 0
c) An exception is thrown
d) 7
View Answer

Answer: d
Explanation: The defaultdict is initialized with a lambda function that returns 7. When the key 4 is accessed and not found, the lambda function is called to provide a default value. So, b[4] returns 7 without raising an error.

15. What will be the output of the following Python code?

import collections
a=collections.OrderedDict((str(x),x) for x in range(3))
print(a)

a) {‘2’:2, ‘0’:0, ‘1’:1}
b) OrderedDict([(‘0’, 0), (‘1’, 1), (‘2’, 2)])
c) An exception is thrown
d) ‘ ‘
View Answer

Answer: b
Explanation: The OrderedDict stores items in the order they are added. The expression creates key-value pairs from 0 to 2 with keys as strings. So, the output maintains insertion order and prints: OrderedDict([(‘0’, 0), (‘1’, 1), (‘2’, 2)]).

Sanfoundry Global Education & Learning Series – Python.

To practice all areas of Python, here is complete set of 1000+ Multiple Choice Questions and Answers.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.