Exercise: Python

Questions for: Dictionaries

How do you check if a key exists in a dictionary without raising an error if the key is not present?
A:
if dictionary.contains(key):
B:
if key.exists_in(dictionary):
C:
if key in dictionary:
D:
if dictionary.has_key(key):
Answer: C
The in keyword is used to check if a key exists in a dictionary.
How do you create a dictionary with default values for keys?
A:
default_dict = dict.default(value)
B:
default_dict = dict.fromkeys(keys, value)
C:
default_dict = dict.create(keys, value)
D:
default_dict = dict(keys, value)
Answer: B
The fromkeys() method is used to create a dictionary with default values for specified keys.
What is the purpose of the dictionary.popitem() method?
A:
Removes the last key-value pair from the dictionary.
B:
Removes a random key-value pair from the dictionary.
C:
Raises a KeyError.
D:
Adds a new key-value pair to the dictionary.
Answer: B
The popitem() method removes a random key-value pair from the dictionary.
How do you check if a key exists in a dictionary and, if not, add a default value to it?
A:
if key not in dictionary: dictionary[key] = default_value
B:
dictionary.check_and_add(key, default_value)
C:
dictionary.ensure_key(key, default_value)
D:
dictionary.add_default(key, default_value)
Answer: A
The provided code checks if the key exists in the dictionary, and if not, adds the key with the specified default value.
What is the result of the expression dictionary.get('key')?
A:
Returns the value for 'key' if present, otherwise returns None.
B:
Raises a KeyError if 'key' is not present.
C:
Returns True if 'key' is present, False otherwise.
D:
Returns a tuple containing 'key' and its value.
Answer: A
The get() method returns the value for 'key' if present, otherwise returns None.
Ad Slot (Above Pagination)
Quiz