开始使用免费开始使用

在字典中检查数据

您可以使用 in 表达式来检查某个键是否存在于字典中。

例如,您可以用 if 'cookies' in recipes: 检查 'cookies' 是否是 recipes 字典中的一个键。这样就能在字典包含该数据时安全地做出处理。

我们已经加载了一个 squirrels_by_park 字典,以公园名称为键,值是松鼠信息的字典列表。

本练习是课程的一部分

Python 的数据类型

查看课程

练习说明

  • 检查 Tompkins Square Park 是否在 squirrels_by_park 字典中,如果存在则打印 'Found Tompkins Square Park'
  • 检查 Central Park 是否在 squirrels_by_park 中。若找到则打印 'Found Central Park',若未找到则打印 'Central Park missing'

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Check to see if Tompkins Square Park is in squirrels_by_park
if "____" ____ ____:
    # Print 'Found Tompkins Square Park'
    print('Found Tompkins Square Park')
    
# Check to see if Central Park is in squirrels_by_park
if "____" ____ ____:
    # Print 'Found Central Park' if found
    print('Found Central Park')
else:
    # Print 'Central Park missing' if not found
    print('Central Park missing')
编辑并运行代码