Latest Python Dictionaries MCQs

1 min read

Python dictionaries are built-in data structures used to store data in key-value pairs, providing fast lookups, insertions, and deletions. Keys must be immutable types like strings, numbers, or tuples, while values can be of any data type and duplicated. They are mutable, meaning they can be modified in place after creation. Understanding dictionaries is essential for efficient data manipulation, handling JSON-like data structures, and optimizing search operations in Python applications.

1. Which of the following is the correct syntax to create an empty dictionary in Python?

a) {}
b) []
c) ()
d) dict[]
Correct Answer: a) {}
Explanation:
An empty dictionary is created using empty curly braces {} or the dict() constructor. Empty square brackets [] create a list, and parentheses () create a tuple.

2. What is the time complexity of looking up a value by its key in a standard Python dictionary on average?

a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Correct Answer: a) O(1)
Explanation:
Python dictionaries are implemented using hash tables, allowing average-case constant time complexity O(1) for lookups, insertions, and deletions.

3. Which of the following data types can be used as a dictionary key in Python?

a) Tuple containing strings and integers
b) List
c) Dictionary
d) Set
Correct Answer: a) Tuple containing strings and integers
Explanation:
Dictionary keys must be immutable and hashable. Tuples are hashable if all their elements are hashable. Lists, dictionaries, and sets are mutable and unhashable.

4. What happens when you try to access a dictionary key using the bracket notation (e.g., d['missing']) when the key does not exist?

a) It raises a KeyError
b) It returns None
c) It raises an IndexError
d) It automatically creates the key with a value of None
Correct Answer: a) It raises a KeyError
Explanation:
Using bracket notation for a non-existent key raises a KeyError. To avoid this, the get() method can be used, which returns None by default.

5. What does the get() method return if the specified key is not found in the dictionary and no default value is provided?

a) None
b) KeyError
c) False
d) 0
Correct Answer: a) None
Explanation:
The dictionary get(key) method safely returns None if the key is absent, whereas bracket notation raises a KeyError.

6. Which method is used to remove and return an arbitrary (key, value) pair from a Python dictionary?

a) popitem()
b) pop()
c) clear()
d) remove()
Correct Answer: a) popitem()
Explanation:
popitem() removes and returns the last inserted (key, value) pair (in Python 3.7+). pop() requires a specific key argument.

7. How can you merge two dictionaries d1 and d2 in Python 3.9 or newer?

a) d1 | d2
b) d1 + d2
c) d1.merge(d2)
d) concat(d1, d2)
Correct Answer: a) d1 | d2
Explanation:
Python 3.9 introduced the union operator (|) for dictionaries, allowing clean merging of two dictionary objects.

8. What does the update() method do when given a key that already exists in the dictionary?

a) It overwrites the existing value with the new value
b) It raises a KeyError
c) It ignores the update
d) It creates a duplicate key entry
Correct Answer: a) It overwrites the existing value with the new value
Explanation:
The update() method updates the dictionary with elements from another dictionary or iterable of key/value pairs, overwriting existing keys.

9. Which built-in function returns a view object displaying a list of all keys in a dictionary?

a) keys()
b) items()
c) values()
d) list_keys()
Correct Answer: a) keys()
Explanation:
The keys() method returns a view object that displays all the keys present in the dictionary.

10. What will happen if you try to use a list as a dictionary key?

a) A TypeError is raised because lists are unhashable
b) It works fine and converts the list to a tuple internally
c) A KeyError is raised
d) The list is converted to a string automatically
Correct Answer: a) A TypeError is raised because lists are unhashable
Explanation:
Lists are mutable and therefore unhashable, causing Python to raise a TypeError when attempting to use them as keys.

11. What does the setdefault() method do if a key is already present in the dictionary?

a) It returns the current value of the key without changing it
b) It overwrites it with the default value provided
c) It raises a KeyError
d) It deletes the key
Correct Answer: a) It returns the current value of the key without changing it
Explanation:
If the key is in the dictionary, setdefault() returns its value. If not, it inserts the key with the specified default value and returns it.

12. How do you remove all items from a dictionary completely?

a) clear()
b) delete()
c) reset()
d) empty()
Correct Answer: a) clear()
Explanation:
The clear() method removes all items from a dictionary, leaving it empty.

13. What is the output of len({'a': 1, 'b': 2, 'c': 3})?

a) 3
b) 6
c) 2
d) 4
Correct Answer: a) 3
Explanation:
The len() function returns the number of key-value pairs in the dictionary, which is 3.

14. Which of the following creates a dictionary with default values from a sequence of keys?

a) dict.fromkeys(seq, value)
b) dict(seq, default=value)
c) dict.defaults(seq, value)
d) dict.create(seq, value)
Correct Answer: a) dict.fromkeys(seq, value)
Explanation:
dict.fromkeys() creates a new dictionary with keys from the given iterable and values set to the specified value (defaulting to None).

15. When iterating over a dictionary using a standard for loop (e.g., for k in d), what does it iterate over?

a) The dictionary's keys
b) The dictionary's values
c) The dictionary's key-value tuples
d) Random items
Correct Answer: a) The dictionary's keys
Explanation:
Iterating over a dictionary directly loops through its keys by default.

16. What does the items() method return?

a) A view object displaying a list of a dictionary's key-value tuple pairs
b) A list of keys
c) A list of values
d) A nested dictionary
Correct Answer: a) A view object displaying a list of a dictionary's key-value tuple pairs
Explanation:
The items() method returns a view object of (key, value) tuples.

17. Which of the following is a valid dictionary comprehension syntax?

a) {k: v for k, v in iterable}
b) [k: v for k, v in iterable]
c) (k: v for k, v in iterable)
d) dict{k: v for k, v in iterable}
Correct Answer: a) {k: v for k, v in iterable}
Explanation:
Dictionary comprehensions use curly braces {} with key: value format separated by a colon.

18. What happens if you assign a value to a dictionary key that already exists?

a) The existing value is updated with the new value
b) A KeyError is raised
c) A new duplicate key is appended
d) The operation is ignored
Correct Answer: a) The existing value is updated with the new value
Explanation:
Dictionary keys are unique; assigning to an existing key overwrites its current value.

19. Which operator is used to check if a key exists in a dictionary?

a) in
b) exists
c) has
d) contains
Correct Answer: a) in
Explanation:
The 'in' operator checks membership against dictionary keys (e.g., 'key' in my_dict).

20. What is the purpose of the pop(key) method in dictionaries?

a) It removes the specified key and returns its corresponding value
b) It removes the last inserted item
c) It clears the entire dictionary
d) It returns the value without removing the key
Correct Answer: a) It removes the specified key and returns its corresponding value
Explanation:
pop(key) removes the key and returns its value. If the key is not found, it raises a KeyError unless a default value is supplied.

21. Can booleans (True and False) be used as dictionary keys in Python?

a) Yes, because booleans are hashable subclasses of integers
b) No, keys must be strings or numbers
c) Only True can be a key, False is reserved
d) Yes, but they are converted to strings automatically
Correct Answer: a) Yes, because booleans are hashable subclasses of integers
Explanation:
Booleans are hashable and immutable, and True/False can be dictionary keys (note that True evaluates to hash of 1 and False to 0).

22. Which statement correctly describes Python dictionary ordering as of Python 3.7+?

a) Dictionaries maintain insertion order
b) Dictionaries are automatically sorted alphabetically by keys
c) Dictionaries are stored in random order
d) Dictionaries are sorted by values
Correct Answer: a) Dictionaries maintain insertion order
Explanation:
Since Python 3.7, standard dictionaries guarantee that insertion order is preserved.

23. What does the values() method return?

a) A view object displaying all values in the dictionary
b) A list of keys
c) A tuple of keys and values
d) A sorted list of values
Correct Answer: a) A view object displaying all values in the dictionary
Explanation:
The values() method returns a view object containing all the values present in the dictionary.

24. How do you create a shallow copy of a dictionary named d?

a) d.copy()
b) copy(d)
c) d.clone()
d) d.shallow()
Correct Answer: a) d.copy()
Explanation:
The copy() method returns a shallow copy of the dictionary.

25. What is the output of {'x': 1, 'y': 2}.get('z', 99)?

a) 99
b) None
c) KeyError
d) 0
Correct Answer: a) 99
Explanation:
Since key 'z' is not in the dictionary, the get() method returns the specified default value of 99.

26. Which keyword or statement is used to delete a specific key-value pair from a dictionary?

a) del
b) remove
c) discard
d) drop
Correct Answer: a) del
Explanation:
The 'del' statement is used to remove an item by its key (e.g., del my_dict['key']).

27. What happens if you pass a dictionary with duplicate keys during dictionary creation (e.g., {'a': 1, 'a': 2})?

a) The later value overwrites the earlier value
b) A SyntaxError is raised
c) A KeyError is raised
d) Both values are kept in a list
Correct Answer: a) The later value overwrites the earlier value
Explanation:
Dictionary keys must be unique. If duplicate keys are specified during initialization, the last occurrence takes precedence.

28. What is the result of 'a' in {'a': 1, 'b': 2}?

a) True
b) False
c) 1
d) KeyError
Correct Answer: a) True
Explanation:
The 'in' operator checks for key presence and returns True because 'a' is a key in the dictionary.

29. Can a dictionary contain values of different data types?

a) Yes, dictionary values can be of any data type and can be mixed
b) No, all values must be of the same data type
c) Only strings and integers are allowed as values
d) No, values must match the type of the keys
Correct Answer: a) Yes, dictionary values can be of any data type and can be mixed
Explanation:
Dictionary values have no restrictions and can be integers, strings, lists, other dictionaries, etc., all mixed together.

30. What does the update() method accept as an argument?

a) Another dictionary or an iterable of key-value pairs (like tuples)
b) Only another dictionary
c) Only lists of keys
d) Single keys only
Correct Answer: a) Another dictionary or an iterable of key-value pairs (like tuples)
Explanation:
The update() method can take either another dictionary object or an iterable of key/value pairs (such as a list of 2-tuples).

31. What is the output of dict(a=1, b=2)?

a) {'a': 1, 'b': 2}
b) ('a': 1, 'b': 2)
c) [('a', 1), ('b', 2)]
d) Error
Correct Answer: a) {'a': 1, 'b': 2}
Explanation:
The dict() constructor accepts keyword arguments where keyword names become dictionary keys.

32. Which of the following is true regarding dictionary view objects?

a) They provide a dynamic view on the dictionary's entries, meaning changes to the dictionary reflect in the view
b) They are static snapshots that never change
c) They are immutable lists stored in memory
d) They support item assignment directly
Correct Answer: a) They provide a dynamic view on the dictionary's entries, meaning changes to the dictionary reflect in the view
Explanation:
Dictionary views (keys(), values(), items()) are dynamic and reflect any subsequent modifications made to the dictionary.

33. What will happen if you attempt to access a dictionary using pop() with a key that does not exist and no default value?

a) It raises a KeyError
b) It returns None
c) It raises an IndexError
d) It returns False
Correct Answer: a) It raises a KeyError
Explanation:
Passing a non-existent key to pop() without a default argument raises a KeyError.

34. What is the time complexity of checking if a value exists in a dictionary (e.g., val in d.values())?

a) O(n)
b) O(1)
c) O(log n)
d) O(n log n)
Correct Answer: a) O(n)
Explanation:
While key lookups are O(1) via hashing, value lookups require scanning all values in the dictionary, resulting in O(n) time complexity.

35. Which method can you use to safely pop an item with a fallback default value if the key is missing?

a) pop(key, default)
b) pop(key, fallback=default)
c) remove(key, default)
d) delete(key, default)
Correct Answer: a) pop(key, default)
Explanation:
The pop() method accepts an optional second argument as a default value returned if the key is not found.

36. What does the expression {x: x**2 for x in range(3)} evaluate to?

a) {0: 0, 1: 1, 2: 4}
b) {0, 1, 4}
c) [0, 1, 4]
d) {1: 1, 2: 4, 3: 9}
Correct Answer: a) {0: 0, 1: 1, 2: 4}
Explanation:
Range(3) yields 0, 1, 2. The dictionary comprehension maps each number x to its square x**2.

37. Can floating-point numbers be used as dictionary keys?

a) Yes, floats are immutable and hashable
b) No, keys must be integers or strings
c) Only if they are whole numbers
d) No, floats cause hash collision errors
Correct Answer: a) Yes, floats are immutable and hashable
Explanation:
Floats are immutable and hashable, making them valid dictionary keys (though using them with caution due to precision issues is recommended).

38. What is the result of merging two dictionaries using the update method (d1.update(d2)) when keys overlap?

a) Values from d2 overwrite values from d1 for the overlapping keys
b) Values from d1 take precedence
c) A KeyError is raised
d) Both values are kept in a list
Correct Answer: a) Values from d2 overwrite values from d1 for the overlapping keys
Explanation:
d1.update(d2) merges d2 into d1, updating d1's values with d2's values where keys overlap.

39. Which of the following built-in functions can sort a dictionary by its keys?

a) sorted(d)
b) d.sort()
c) sort(d)
d) d.order_by_keys()
Correct Answer: a) sorted(d)
Explanation:
Passing a dictionary to sorted() returns a sorted list of its keys.

40. What does the expression 1 in {1: 'a', 2: 'b'} evaluate to?

a) True
b) False
c) 'a'
d) 1
Correct Answer: a) True
Explanation:
The 'in' operator checks if 1 is a key in the dictionary, returning True.

41. What is the output of {'a': 1}.keys()?

a) dict_keys(['a'])
b) ['a']
c) ('a',)
d) {'a'}
Correct Answer: a) dict_keys(['a'])
Explanation:
The keys() method returns a dict_keys view object, not a standard list.

42. How can you convert a dictionary's keys into a standard Python list?

a) list(d.keys())
b) d.keys.to_list()
c) Array(d.keys())
d) d.tolist()
Correct Answer: a) list(d.keys())
Explanation:
Passing the dict keys view to the list() constructor converts it into a standard list.

43. What happens when you use the dict() constructor with a list of two-element tuples?

a) It creates a dictionary where the first element of each tuple is the key and the second is the value
b) It raises a TypeError
c) It creates a nested dictionary
d) It creates a set of tuples
Correct Answer: a) It creates a dictionary where the first element of each tuple is the key and the second is the value
Explanation:
dict([('k1', 'v1'), ('k2', 'v2')]) correctly builds a dictionary from key-value pairs.

44. Which of the following represents a nested dictionary?

a) {'person': {'name': 'Alice', 'age': 30}}
b) {'person': ['Alice', 30]}
c) {'person', {'name': 'Alice'}}
d) [{'person': 'Alice'}]
Correct Answer: a) {'person': {'name': 'Alice', 'age': 30}}
Explanation:
A nested dictionary is a dictionary in which one or more values are themselves dictionaries.

45. How do you access the value 'Alice' from a nested dictionary d = {'person': {'name': 'Alice'}}?

a) d['person']['name']
b) d['person, name']
c) d['person']['name'](https://www.google.com/search?q=)
d) d.person.name
Correct Answer: a) d['person']['name']
Explanation:
Chained bracket notation is used to access values inside nested dictionaries.

46. What is the return type of the items() method in Python 3?

a) dict_items
b) list
c) tuple
d) set
Correct Answer: a) dict_items
Explanation:
items() returns a view object of type dict_items.

47. Which operator performs in-place dictionary merging introduced in Python 3.9?

a) |=
b) +=
c) &=
d) >>=
Correct Answer: a) |=
Explanation:
The update-or-union assignment operator (|-) updates the dictionary in-place with another dictionary's contents.

48. What will { {'a': 1}, {'b': 2}} evaluate to?

a) {'a': 1, 'b': 2}
b) {'a': 1}, {'b': 2}
c) {'a': {'b': 2}}
d) Error
Correct Answer: a) {'a': 1, 'b': 2}
Explanation:
Dictionary unpacking using the double asterisk (**) operator merges dictionaries (pre-Python 3.9 merging technique).

49. Can strings be used as dictionary keys?

a) Yes, strings are immutable and hashable, making them the most common dictionary keys
b) No, strings are mutable sequences
c) Only single-character strings are allowed
d) Only if converted to bytes first
Correct Answer: a) Yes, strings are immutable and hashable, making them the most common dictionary keys
Explanation:
Strings are immutable, hashable, and frequently used as keys in Python dictionaries.

50. What is the output of len({})?

a) 0
b) 1
c) None
d) Error
Correct Answer: a) 0
Explanation:
An empty dictionary has a length of 0.

51. Which method allows you to set a default value for a key only if that key does not already exist?

a) setdefault()
b) update()
c) get()
d) put()
Correct Answer: a) setdefault()
Explanation:
setdefault() inserts the key with a default value if the key is not already present.

52. What happens if you try to delete a non-existent key using the del statement (e.g., del d['missing'])?

a) It raises a KeyError
b) It returns None silently
c) It raises an IndexError
d) It ignores the statement
Correct Answer: a) It raises a KeyError
Explanation:
Using del on a missing key raises a KeyError.

53. Which of the following is an unhashable type and therefore CANNOT be a dictionary key?

a) Set
b) Tuple
c) String
d) Integer
Correct Answer: a) Set
Explanation:
Sets are mutable and unhashable, so they cannot be used as dictionary keys.

54. How do you iterate over both keys and values simultaneously in a for loop?

a) for k, v in d.items():
b) for k, v in d:
c) for k, v in d.keys():
d) for k, v in d.values():
Correct Answer: a) for k, v in d.items():
Explanation:
d.items() yields (key, value) pairs, which can be unpacked directly in a for loop header.

55. What is the output of dict([('a', 1), ('b', 2)]).get('c', 0)?

a) 0
b) None
c) KeyError
d) 1
Correct Answer: a) 0
Explanation:
Since 'c' is not present, get() returns the provided default value of 0.

56. Which of the following statements about dictionary keys is true?

a) Keys must be unique
b) Keys must be strings
c) Keys must be integers
d) Keys can be duplicated if values are different
Correct Answer: a) Keys must be unique
Explanation:
Dictionary keys must be unique within a dictionary; duplicate keys are not allowed.

57. What does the expression 'b' in {'a': 1, 'b': 2}.values() evaluate to?

a) False
b) True
c) 'b'
d) KeyError
Correct Answer: a) False
Explanation:
The 'in' operator on a dictionary checks keys, not values. To check values, you must use 'b' in d.values().

58. What is the result of dict.fromkeys(['a', 'b'], 0)?

a) {'a': 0, 'b': 0}
b) {'a': ['b', 0]}
c) {0: 'a', 0: 'b'}
d) Error
Correct Answer: a) {'a': 0, 'b': 0}
Explanation:
dict.fromkeys() assigns the specified value (0) to each key in the iterable ['a', 'b'].

59. Which of the following methods removes the last inserted item in Python 3.7+?

a) popitem()
b) pop()
c) clear()
d) discard()
Correct Answer: a) popitem()
Explanation:
popitem() removes and returns the last inserted (key, value) pair due to ordered dictionary guarantees.

60. What happens if you modify a dictionary while iterating over its keys directly?

a) A RuntimeError is raised due to dictionary size changing during iteration
b) The iteration automatically adapts to the new size
c) It skips newly added keys
d) It loops infinitely
Correct Answer: a) A RuntimeError is raised due to dictionary size changing during iteration
Explanation:
Modifying a dictionary's size during iteration directly triggers a RuntimeError. To modify safely, iterate over a list of keys (e.g., list(d)).

61. What is the output of {'a': 1} == {'a': 1}?

a) True
b) False
c) None
d) Error
Correct Answer: a) True
Explanation:
Dictionaries compare equal if they contain the exact same key-value pairs, regardless of insertion order.

62. Can frozen sets be used as dictionary keys?

a) Yes, because frozensets are immutable and hashable
b) No, sets and frozensets are never hashable
c) Only if they contain strings
d) No, only tuples are allowed
Correct Answer: a) Yes, because frozensets are immutable and hashable
Explanation:
Frozensets are immutable variants of sets, making them hashable and valid dictionary keys.

63. What does the expression {x: x for x in 'ab'} produce?

a) {'a': 'a', 'b': 'b'}
b) {'a', 'b'}
c) ['a', 'b']
d) {'ab': 'ab'}
Correct Answer: a) {'a': 'a', 'b': 'b'}
Explanation:
The dictionary comprehension sets both key and value to each character from the string 'ab'.

64. How do you count the frequency of elements in a list using a standard dictionary pattern?

a) d[item] = d.get(item, 0) + 1
b) d[item] += 1
c) d.add(item)
d) d.count(item)
Correct Answer: a) d[item] = d.get(item, 0) + 1
Explanation:
Using get(item, 0) safely handles missing keys by defaulting to 0 before incrementing the frequency count.

65. What is the output of dict(zip(['a', 'b'], [1, 2]))?

a) {'a': 1, 'b': 2}
b) [('a', 1), ('b', 2)]
c) {'a', 'b', 1, 2}
d) Error
Correct Answer: a) {'a': 1, 'b': 2}
Explanation:
zip() pairs keys and values together, and dict() converts the zipped pairs into a dictionary.

66. Which module in Python's standard library provides a dictionary subclass that remembers insertion order prior to Python 3.7?

a) collections (OrderedDict)
b) itertools
c) functools
d) operator
Correct Answer: a) collections (OrderedDict)
Explanation:
Before standard dicts became ordered in Python 3.7, collections.OrderedDict was used to maintain insertion order.

67. What is the output of collections.defaultdict(int)['missing']?

a) 0
b) None
c) KeyError
d) 1
Correct Answer: a) 0
Explanation:
defaultdict with int factory initializes missing keys with the default integer value, which is 0.

68. What is the output of collections.defaultdict(list)['missing']?

a) []
b) None
c) KeyError
d)
Correct Answer: a) []
Explanation:
defaultdict with list factory initializes missing keys with an empty list [] via list().

69. What does the expression {**{'a': 1}, 'a': 2} evaluate to?

a) {'a': 2}
b) {'a': 1}
c) {'a': 1, 'a': 2}
d) Error
Correct Answer: a) {'a': 2}
Explanation:
Unpacking {'a': 1} and then providing 'a': 2 overrides the key 'a' with the value 2.

70. Can a dictionary key be an integer?

a) Yes, integers are immutable and hashable
b) No, keys must always be strings
c) Only positive integers are allowed
d) No, integers are converted to strings
Correct Answer: a) Yes, integers are immutable and hashable
Explanation:
Integers are immutable and hashable, making them completely valid dictionary keys.

71. What is the primary difference between a dictionary and a list?

a) Dictionaries store data as key-value pairs accessed via keys, while lists store ordered elements accessed via integer indices
b) Lists are faster than dictionaries for all operations
c) Dictionaries do not allow duplicate values
d) Lists are mutable while dictionaries are immutable
Correct Answer: a) Dictionaries store data as key-value pairs accessed via keys, while lists store ordered elements accessed via integer indices
Explanation:
Lists use integer indices for sequence storage, whereas dictionaries use arbitrary hashable keys for associative mapping.

72. What happens when you call popitem() on an empty dictionary?

a) It raises a KeyError
b) It returns None
c) It raises an IndexError
d) It returns an empty tuple
Correct Answer: a) It raises a KeyError
Explanation:
Calling popitem() on an empty dictionary raises a KeyError because there are no items to remove.

73. Which of the following method calls returns a list of all values in a dictionary sorted in ascending order?

a) sorted(d.values())
b) d.values().sort()
c) sorted(d).values()
d) d.sort_values()
Correct Answer: a) sorted(d.values())
Explanation:
sorted() takes an iterable (like d.values()) and returns a new sorted list containing those values.

74. What is the output of {'a': 1, 'b': 2}.get('a')?

a) 1
b) 'a'
c) None
d) KeyError
Correct Answer: a) 1
Explanation:
The get() method retrieves the value associated with the specified key 'a', which is 1.

75. How do you check the number of items in a dictionary named my_dict?

a) len(my_dict)
b) my_dict.length()
c) size(my_dict)
d) my_dict.size()
Correct Answer: a) len(my_dict)
Explanation:
The built-in len() function returns the count of key-value pairs in a dictionary.

76. What does the expression {x: x*2 for x in [1, 2, 3] if x > 1} evaluate to?

a) {2: 4, 3: 6}
b) {1: 2, 2: 4, 3: 6}
c) {2: 2, 3: 3}
d) {4: 2, 6: 3}
Correct Answer: a) {2: 4, 3: 6}
Explanation:
The filter 'if x > 1' selects 2 and 3. Mapping each to x*2 yields {2: 4, 3: 6}.

77. Which of the following is NOT a valid way to initialize a dictionary in Python?

a) dict([1, 2, 3])
b) {}
c) dict(a=1, b=2)
d) dict([('a', 1), ('b', 2)])
Correct Answer: a) dict([1, 2, 3])
Explanation:
dict() expects an iterable of key-value pairs (like 2-tuples). Passing a plain list of integers like [1, 2, 3] raises a TypeError.

78. What is the output of {'a': 1, 'b': 2}.popitem()?

a) ('b', 2)
b) ('a', 1)
c) 'b'
d) 2
Correct Answer: a) ('b', 2)
Explanation:
popitem() removes and returns the last inserted item as a (key, value) tuple, which is ('b', 2).

79. Can a dictionary contain duplicate values?

a) Yes, values can be duplicated across different keys
b) No, values must be completely unique just like keys
c) Only if the keys are integers
d) No, duplicate values raise a ValueError
Correct Answer: a) Yes, values can be duplicated across different keys
Explanation:
While dictionary keys must be unique, multiple keys can map to the exact same value.

80. What does the expression 'a' not in {'a': 1} evaluate to?

a) False
b) True
c) None
d) Error
Correct Answer: a) False
Explanation:
Since 'a' is present as a key, 'a' not in dictionary evaluates to False.

81. Which of the following functions can be used to iterate over a dictionary with both index and key-value pairs?

a) enumerate(d.items())
b) zip(d)
c) index(d)
d) enumerate(d)
Correct Answer: a) enumerate(d.items())
Explanation:
enumerate() combined with d.items() yields an index alongside each key-value pair.

82. What is the output of dict(a=1, b=2).get('b')

a) 2
b) 'b'
c) 1
d) None
Correct Answer: a) 2
Explanation:
The get() method returns the value associated with key 'b', which is 2.

83. How do you clear a dictionary d without reassigning the variable name?

a) d.clear()
b) d = {}
c) d.delete_all()
d) del d
Correct Answer: a) d.clear()
Explanation:
d.clear() empties the existing dictionary in-place, whereas d = {} creates a new empty dictionary object.

84. What is the return type of dict.keys()?

a) dict_keys
b) list
c) set
d) tuple
Correct Answer: a) dict_keys
Explanation:
dict.keys() returns a view object of type dict_keys.

85. What happens when you pass an empty iterable to dict.fromkeys()?

a) It returns an empty dictionary {}
b) It raises a ValueError
c) It returns None
d) It raises a KeyError
Correct Answer: a) It returns an empty dictionary {}
Explanation:
Passing an empty iterable generates no keys, resulting in an empty dictionary.

86. Which of the following sorting approaches sorts a dictionary by its values in descending order?

a) sorted(d.items(), key=lambda item: item[1], reverse=True)
b) d.values().sort(reverse=True)
c) sorted(d, reverse=True)
d) d.sort(key=value)
Correct Answer: a) sorted(d.items(), key=lambda item: item[1], reverse=True)
Explanation:
Sorting d.items() with a lambda key targeting element 1 (the value) and reverse=True produces a list of key-value pairs sorted by value descending.

87. What is the output of {'a': 1}.setdefault('b', 5)?

a) 5
b) 1
c) None
d) KeyError
Correct Answer: a) 5
Explanation:
Since 'b' is missing, setdefault() inserts 'b': 5 into the dictionary and returns the newly inserted value 5.

88. What does the expression list({'a': 1, 'b': 2}) return?

a) ['a', 'b']
b) [1, 2]
c) [('a', 1), ('b', 2)]
d) ['a', 1, 'b', 2]
Correct Answer: a) ['a', 'b']
Explanation:
Iterating over or casting a dictionary directly to a list produces a list of its keys.

89. Can bytes objects be used as dictionary keys?

a) Yes, bytes are immutable and hashable
b) No, keys must be text strings
c) Only if converted to bytearrays
d) No, bytes are mutable
Correct Answer: a) Yes, bytes are immutable and hashable
Explanation:
Bytes are immutable sequences and are fully hashable, making them valid dictionary keys.

90. What is the time complexity of the clear() method on a dictionary of size n?

a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Correct Answer: a) O(1)
Explanation:
Clearing a dictionary resets its internal hash table pointers in constant time O(1).

91. How can you check if a dictionary is empty?

a) if not d:
b) if d.empty():
c) if len(d) == 0:
d) Both a and c
Correct Answer: d) Both a and c
Explanation:
Both checking truthiness (`if not d:`) and checking length (`if len(d) == 0:`) are valid, idiomatic ways to check for an empty dictionary.
← Previous: Latest JavaScript Basics MCQs
Next →: Latest Python Loops MCQs
C++ Memory Management MCQs

C++ Memory Management MCQs

Memory management in C++ empowers developers with direct control over hardware resources, primarily through the allocation and deallocation of memory…

By MCQs Generator
JavaScript Operators MCQs

JavaScript Operators MCQs

JavaScript operators are foundational symbols and keywords used to manipulate data, perform mathematical computations, assign values, and control programmatic flow…

By MCQs Generator
Python Interview Questions MCQs

Python Interview Questions MCQs

Python technical interviews evaluate a candidate’s grasp of both fundamental language features and deep runtime execution mechanics. Key topics frequently…

By MCQs Generator