Working with dictionaries more pythonically
So far, you've worked a lot with the keys of a dictionary to access data, but
in Python, the preferred manner for iterating over items in a dictionary is with the
.items()
method.
This returns each key and value from the dictionary as a tuple, which you can unpack in a for
loop. You'll now get practice doing this.
We've loaded a squirrels_by_park
dictionary, and the Madison Square Park
key contains a list of dictionaries.
This exercise is part of the course
Data Types in Python
Exercise instructions
- Iterate over the first record in
squirrels_by_park["Madison Square Park"]
, unpacking its items intofield
andvalue
.- Print each
field
andvalue
.
- Print each
- Repeat the process for the second record in
squirrels_by_park["Union Square Park"]
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Iterate over the first squirrel entry in the Madison Square Park list
for ____, ____ in ____["____"][____].____():
# Print field and value
print(____, ____)
print('-' * 13)
# Iterate over the second squirrel entry in the Union Square Park list
____
# Print field and value
____