Python Programming - Dictionaries

Exercise : Dictionaries - General Questions
  • Dictionaries - General Questions
31.
What is the purpose of the dictionary.popitem() method?
Removes the last key-value pair from the dictionary.
Removes a random key-value pair from the dictionary.
Raises a KeyError.
Adds a new key-value pair to the dictionary.
Answer: Option
Explanation:
The popitem() method removes a random key-value pair from the dictionary.

32.
How do you merge two dictionaries?
merged_dict = dict.merge(dictionary1, dictionary2)
merged_dict = dictionary1.combine(dictionary2)
dictionary1.update(dictionary2)
merged_dict = dictionary1 + dictionary2
Answer: Option
Explanation:
The update() method is used to merge two dictionaries in Python.

33.
How do you create a dictionary with default values for keys?
default_dict = dict.default(value)
default_dict = dict.fromkeys(keys, value)
default_dict = dict.create(keys, value)
default_dict = dict(keys, value)
Answer: Option
Explanation:
The fromkeys() method is used to create a dictionary with default values for specified keys.

34.
How do you check if a key exists in a dictionary without raising an error if the key is not present?
if dictionary.contains(key):
if key.exists_in(dictionary):
if key in dictionary:
if dictionary.has_key(key):
Answer: Option
Explanation:
The in keyword is used to check if a key exists in a dictionary.

35.
How do you extract all values from a dictionary and store them in a list?
values_list = dictionary.get_values()
values_list = list(dictionary.values())
values_list = dictionary.extract_values()
values_list = dictionary.all_values()
Answer: Option
Explanation:
The values() method is used to extract all values from a dictionary, and list() is used to convert it into a list.