Exercise: Python

Questions for: Dictionaries

What is the result of the expression len(dictionary)?
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: A
The len() function returns the number of keys in a dictionary.
How do you remove a key-value pair from a dictionary?
A:
dictionary.remove_key(key)
B:
dictionary.delete(key)
C:
dictionary.remove(key)
D:
dictionary.pop(key)
Answer: D
The pop() method is used to remove a key-value pair from a dictionary.
What is the purpose of the dictionary.setdefault(key, default_value) method?
A:
Sets the default value for a key.
B:
Retrieves the default value for a key.
C:
Adds a new key-value pair with a default value.
D:
Removes a key from the dictionary.
Answer: A
The setdefault() method sets the default value for a key if the key is not present in the dictionary.
How do you retrieve all keys from a dictionary?
A:
dictionary.keys()
B:
dictionary.get_keys()
C:
dictionary.extract_keys()
D:
dictionary.all_keys()
Answer: A
The keys() method is used to retrieve all keys from a dictionary.
How do you check if a key is present in a dictionary?
A:
key.exists()
B:
key.in()
C:
key.present()
D:
key in dictionary
Answer: D
The in keyword is used to check if a key is present in a dictionary.
Ad Slot (Above Pagination)
Quiz