Creating and looping through dictionaries
You'll often encounter the need to loop over some array type data, like in Chapter 1, and provide it some structure so you can find the data you desire quickly.
You start that by creating an empty dictionary and assigning part of your array data as the key and the rest as the value.
Previously, you used sorted()
to organize your data in a list. Dictionaries can also be sorted. By default, using sorted()
on a dictionary will sort by the keys of the dictionary.
The goal of this exercise is to get familiar with building dictionaries via looping over some data source, and then looping over the dictionary to use that data.
This exercise is part of the course
Data Types in Python
Exercise instructions
- Create an empty dictionary called
squirrels_by_park
. - Loop over
squirrels
, unpacking it into the variablespark
andsquirrel_details
. - Inside the loop, add each
squirrel_details
to thesquirrels_by_park
dictionary using thepark
as the key. - Sort the
squirrel_details
dictionary keys in ascending order, print each park and its value using an F string..
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create an empty dictionary: squirrels_by_park
____ = ____
# Loop over the squirrels list and unpack each tuple
for ____, ____ in ____:
# Add each squirrel_details to the squirrels_by_park dictionary
____[____] = ____
# Sort the squirrels_by_park dict alphabetically by park
for park in ____(squirrels_by_park):
# Print each park and its value in squirrels_by_park
print(f'{____}: {____[____]}')