Quiz 9: How to work with dictionaries
How many items does the following dictionary contain? flowers = {"red": "rose", "white": "lily", "yellow": "buttercup"}
3
Consider the following code: pets = { "dog": {"type": "poodle", "color": "white"}, "cat": {"type": "Siamese", "color": "black and white"}, "bird": {"type": "parrot", "color": "green"} } pet = pets["dog"] pet = pets["bird"] print(pet["color"], pet["type"]) What will display after the code executes?
NOT white poodle
Each item in a dictionary is
a key/value pair
The key in a dictionary can be
any immutable type
To convert a view object to a list, you can use the To delete all items from a dictionary you can
list() constructor
Consider the following code: pets = { "dog": {"type": "poodle", "color": "white"}, "cat": {"type": "Siamese", "color": "black and white"}, "bird": {"type": "parrot", "color": "green"} } pet = pets["dog"] pet = pets["bird"] print(pet["color"], pet["type"]) Which of the following could you add to the end of this example to print "black and white Siamese cat" to the console?
pet = "cat" print(pets[pet]["color"], pets[pet]["type"], pet)
A dictionary stores a collection of
unordered items
To delete all items from a dictionary you can
use the clear() method
The items() method returns a
view object containing all of the key/value pairs in a dictionary
The keys() method returns a
view object containing all of the keys in a dictionary