Exercise: Python

Questions for: Dictionaries

What does the dictionary.clear() method do?
A:
Removes a specific key-value pair.
B:
Removes all items from the dictionary.
C:
Clears the values of the dictionary.
D:
Deletes the dictionary itself.
Answer: B
The clear() method removes all items from a dictionary.
What is the purpose of the dictionary.update(another_dict) method?
A:
Merges the two dictionaries, updating values for common keys.
B:
Adds a new key-value pair to the dictionary.
C:
Removes a key-value pair from the dictionary.
D:
Creates a new dictionary by combining keys and values.
Answer: A
The update() method merges two dictionaries, updating values for common keys.
How do you create an empty dictionary?
A:
empty_dict = {}
B:
empty_dict = dict.empty()
C:
empty_dict = new Dictionary()
D:
empty_dict = dict()
Answer: A
An empty dictionary in Python can be created using curly braces {}.
How do you remove a key-value pair from a dictionary in Python without raising an error if the key is not present?
A:
dictionary.remove_key(key)
B:
dictionary.delete(key)
C:
dictionary.remove(key)
D:
dictionary.pop(key, None)
Answer: D
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.
What is the result of the expression len(dictionary.values())?
A:
Returns the number of keys in the dictionary.
B:
Returns the number of values in the dictionary.
C:
Returns the total number of key-value pairs.
D:
Raises a TypeError.
Answer: B
The len() function returns the number of values in a dictionary.
Ad Slot (Above Pagination)
Quiz