Exercise: Python

Questions for: Dictionaries

How do you check if a key exists in a dictionary using the get() method?
A:
if key.get(dictionary):
B:
if key.exists_in(dictionary.get()):
C:
if dictionary.get(key) is not None:
D:
if key in dictionary.get():
Answer: C
The get() method returns None if the key is not present, so checking for is not None verifies key existence.
What is the difference between the dictionary.keys() and dictionary.values() methods?
A:
Both methods return the keys of the dictionary.
B:
Both methods return the values of the dictionary.
C:
dictionary.keys() returns a list of keys, while dictionary.values() returns a list of values.
D:
dictionary.keys() returns a list of values, while dictionary.values() returns a list of keys.
Answer: C
The keys() method returns a list of keys, and the values() method returns a list of values in a dictionary.
How do you remove a specific key-value pair from a dictionary?
A:
dictionary.remove(key)
B:
dictionary.delete(key)
C:
dictionary.clear(key)
D:
del dictionary[key]
Answer: D
The del keyword is used to remove a specific key-value pair from a dictionary.
What is the purpose of the dictionary.update(key=value) method?
A:
Adds a new key-value pair to the dictionary.
B:
Updates the values of the dictionary with new values.
C:
Removes a key-value pair from the dictionary.
D:
Raises a SyntaxError.
Answer: A
The update() method with key=value adds a new key-value pair to the dictionary.
How do you create a dictionary with keys from one list and values from another list?
A:
dict(keys, values)
B:
dict.fromkeys(keys, values)
C:
{key: value for key, value in zip(keys, values)}
D:
dictionary.create(keys, values)
Answer: C
Using a dictionary comprehension with zip() can create a dictionary with keys from one list and values from another.
Ad Slot (Above Pagination)
Quiz