Exercise: Python

Questions for: Dictionaries

How do you remove all items from a dictionary?
A:
dictionary.delete_all()
B:
dictionary.clear()
C:
dictionary.remove_all()
D:
dictionary.erase()
Answer: B
The clear() method removes all items from a dictionary.
What is the result of the expression dictionary.get('key', 'default')?
A:
Raises a KeyError if 'key' is not present.
B:
Returns the value of 'key' if present, otherwise returns 'default'.
C:
Returns 'default' if 'key' is not present.
D:
Returns a tuple containing 'key' and its value.
Answer: B
The get() method returns the value for 'key' if present, otherwise returns the specified default value.
How do you create a dictionary with a default value for all new keys?
A:
dictionary.set_default(default_value)
B:
dictionary.default_value = default_value
C:
dictionary.default(default_value)
D:
collections.defaultdict(default_value)
Answer: D
The defaultdict from the collections module is used to create a dictionary with a default value for all new keys.
What is the purpose of the dictionary.items() method?
A:
Returns a list of all keys.
B:
Returns a list of all values.
C:
Returns a list of key-value pairs.
D:
Returns a list of default values.
Answer: C
The items() method returns a list of key-value pairs in the dictionary.
How do you merge two dictionaries?
A:
dict.merge(another_dict)
B:
dict.join(another_dict)
C:
dict + another_dict
D:
dict.update(another_dict)
Answer: D
The update() method is used to merge two dictionaries in Python.
Ad Slot (Above Pagination)
Quiz