Exercise: Python

Questions for: Dictionaries

What does the expression len(dictionary.items()) return?
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: C
The items() method returns a list of key-value pairs, and len() returns the number of items, which is the total number of key-value pairs.
What is the purpose of the dictionary.pop(key, default_value) method?
A:
Removes the specified key from the dictionary.
B:
Raises a KeyError if the key is not present.
C:
Removes the specified key and returns its value, or returns the default value if the key is not present.
D:
Adds a new key-value pair with a default value.
Answer: C
The pop() method with a default value removes the specified key and returns its value, or returns the default value if the key is not present.
How do you check if a specific value exists in the values of a dictionary?
A:
if value in dictionary:
B:
if value.exists_in(dictionary.values()):
C:
if value.contains(dictionary.values()):
D:
if dictionary.contains_value(value):
Answer: A
The in keyword is used to check if a specific value exists in the values of a dictionary.
What does the dictionary.pop(key, None) method do?
A:
Removes the specified key from the dictionary.
B:
Raises a KeyError if the key is not present.
C:
Removes a random key-value pair from the dictionary.
D:
Removes the specified key and returns its value, or returns None if the key is not present.
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.
How do you extract all values from a dictionary and store them in a list?
A:
values_list = dictionary.get_values()
B:
values_list = list(dictionary.values())
C:
values_list = dictionary.extract_values()
D:
values_list = dictionary.all_values()
Answer: B
The values() method is used to extract all values from a dictionary, and list() is used to convert it into a list.
Ad Slot (Above Pagination)
Quiz