更 Pythonic 地使用字典
到目前为止,您主要是通过字典的键来访问数据。但在 Python 中,遍历字典条目的首选方式是使用 .items() 方法。
该方法会将字典中的每个键和值作为一个元组返回,您可以在 for 循环中对其进行解包。接下来,您将练习这种用法。
我们已加载了一个 squirrels_by_park 字典,其中 Madison Square Park 键对应的是一个由字典组成的列表。
本练习是课程的一部分
Python 的数据类型
练习说明
- 遍历
squirrels_by_park["Madison Square Park"]中的第一条记录,将其条目解包为field和value。- 打印每个
field和value。
- 打印每个
- 对
squirrels_by_park["Union Square Park"]中的第二条记录重复上述过程。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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
____