Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Data Types in Python

Cursus bekijken

Oefeninstructies

  • Iterate over the first record in squirrels_by_park["Madison Square Park"], unpacking its items into field and value.
    • Print each field and value.
  • Repeat the process for the second record in squirrels_by_park["Union Square Park"].

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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
    ____
Code bewerken en uitvoeren