Python Programming - Dictionaries

Exercise : Dictionaries - General Questions
  • Dictionaries - General Questions
36.
What does the dictionary.pop(key, None) method do?
Removes the specified key from the dictionary.
Raises a KeyError if the key is not present.
Removes a random key-value pair from the dictionary.
Removes the specified key and returns its value, or returns None if the key is not present.
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.

37.
How do you check if a specific value exists in the values of a dictionary?
if value in dictionary:
if value.exists_in(dictionary.values()):
if value.contains(dictionary.values()):
if dictionary.contains_value(value):
Answer: Option
Explanation:
The in keyword is used to check if a specific value exists in the values of a dictionary.

38.
What is the purpose of the dictionary.pop(key, default_value) method?
Removes the specified key from the dictionary.
Raises a KeyError if the key is not present.
Removes the specified key and returns its value, or returns the default value if the key is not present.
Adds a new key-value pair with a default value.
Answer: Option
Explanation:
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.

39.
What does the expression len(dictionary.items()) return?
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 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.

40.
How do you create a dictionary with keys from one list and values from another list?
dict(keys, values)
dict.fromkeys(keys, values)
{key: value for key, value in zip(keys, values)}
dictionary.create(keys, values)
Answer: Option
Explanation:
Using a dictionary comprehension with zip() can create a dictionary with keys from one list and values from another.