Adding and extending dictionaries
If you have a dictionary and you want to add data to it, you can simply create a new key and assign the data you desire to it. It's important to remember that if it's a nested dictionary, then all the keys in the data path must exist, and each key in the path must be assigned individually.
You can also use the .update() method to update a dictionary with a list of keys and values from another dictionary, tuples or keyword arguments.
The squirrels_by_park dictionary is already loaded for you, which is keyed by the park name and the value is a tuple with the main color, highlights, action, and reaction to humans.
This exercise is part of the course
Data Types in Python
Exercise instructions
- Assign the
squirrels_madisonlist as the value to the'Madison Square Park'key of thesquirrels_by_parkdictionary. - Update the
'Union Square Park'key in thesquirrels_by_parkdictionary with the data in thesquirrels_uniontuple. - Loop over the
squirrels_by_parkdictionary.- Print the
park_nameand a list of allprimary_fur_colors for squirrels safely in that park using a list comprehension; return'N/A'if the key isn't found.
- Print the
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Assign squirrels_madison as the value to the 'Madison Square Park' key
____[____] = ____
# Update squirrels_by_park with the squirrels_union tuple
____.____([____])
# Loop over the park_name in the squirrels_by_park dictionary
for park_name in ____:
# Safely print a list of the primary_fur_color for each squirrel in park_name
print(park_name, [____.get('____', '____') for squirrel in ____[____]])