Python Programming - Dictionaries

Exercise : Dictionaries - General Questions
  • Dictionaries - General Questions
26.
What does the dictionary.clear() method do?
Removes a specific key-value pair.
Removes all items from the dictionary.
Clears the values of the dictionary.
Deletes the dictionary itself.
Answer: Option
Explanation:
The clear() method removes all items from a dictionary.

27.
What is the result of the expression dictionary.get('key')?
Returns the value for 'key' if present, otherwise returns None.
Raises a KeyError if 'key' is not present.
Returns True if 'key' is present, False otherwise.
Returns a tuple containing 'key' and its value.
Answer: Option
Explanation:
The get() method returns the value for 'key' if present, otherwise returns None.

28.
How do you remove a key-value pair from a dictionary in Python without raising an error if the key is not present?
dictionary.remove_key(key)
dictionary.delete(key)
dictionary.remove(key)
dictionary.pop(key, None)
Answer: Option
Explanation:
The pop() method with a default value of None removes a key-value pair from a dictionary without raising an error if the key is not present.

29.
What is the purpose of the dictionary.copy() method?
Creates a shallow copy of the dictionary.
Creates a deep copy of the dictionary.
Copies only the keys of the dictionary.
Copies only the values of the dictionary.
Answer: Option
Explanation:
The copy() method creates a shallow copy of the dictionary.

30.
How do you check if a key exists in a dictionary and, if not, add a default value to it?
if key not in dictionary: dictionary[key] = default_value
dictionary.check_and_add(key, default_value)
dictionary.ensure_key(key, default_value)
dictionary.add_default(key, default_value)
Answer: Option
Explanation:
The provided code checks if the key exists in the dictionary, and if not, adds the key with the specified default value.