MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Data Types in Python

Lihat Kursus

Petunjuk latihan

  • 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"].

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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
    ____
Edit dan Jalankan Kode