Python Programming - Dictionaries

Exercise : Dictionaries - General Questions
  • Dictionaries - General Questions
1.
How do you check if a key is present in a dictionary?
key.exists()
key.in()
key.present()
key in dictionary
Answer: Option
Explanation:
The in keyword is used to check if a key is present in a dictionary.

2.
How do you retrieve all keys from a dictionary?
dictionary.keys()
dictionary.get_keys()
dictionary.extract_keys()
dictionary.all_keys()
Answer: Option
Explanation:
The keys() method is used to retrieve all keys from a dictionary.

3.
What is the purpose of the dictionary.setdefault(key, default_value) method?
Sets the default value for a key.
Retrieves the default value for a key.
Adds a new key-value pair with a default value.
Removes a key from the dictionary.
Answer: Option
Explanation:
The setdefault() method sets the default value for a key if the key is not present in the dictionary.

4.
How do you remove a key-value pair from a dictionary?
dictionary.remove_key(key)
dictionary.delete(key)
dictionary.remove(key)
dictionary.pop(key)
Answer: Option
Explanation:
The pop() method is used to remove a key-value pair from a dictionary.

5.
What is the result of the expression len(dictionary)?
Returns the number of keys in the dictionary.
Returns the number of values in the dictionary.
Returns the total number of key-value pairs.
Raises a TypeError.
Answer: Option
Explanation:
The len() function returns the number of keys in a dictionary.