开始使用免费开始使用

创建结构未知的字典

有时,您需要一个用于存放嵌套数据的结构,但无法确定所有键是否都存在。如果您要向某个键对应的列表追加元素,这就会成为问题。您可能还记得我们在视频中探索的 NYC 数据。若要用常规字典解决这个问题,您需要先测试该键是否存在;如果不存在,就为它添加一个空列表。

本练习中,您将处理一组记录列表,其中包含本研究中雌性企鹅的物种、鳍长、体重和性别。下一道练习里,您将用更简单的方法来解决同类问题。

本练习是课程的一部分

Python 的数据类型

查看课程

练习说明

  • 创建一个名为 female_penguin_weights 的空字典。
  • 遍历 weight_log,并将其解包到变量 speciessexbody_mass
  • 检查 female_penguin_weights 字典中是否已存在该物种。如果存在,则为该物种键创建一个空列表。然后,将由 sexbody_mass 组成的元组追加到 female_penguin_weights 字典中对应 species 的键下,处理 weight_log 中的所有记录。
  • 打印 'Adlie'female_penguin_weights

交互式实操练习

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

# Create an empty dictionary: female_penguin_weights
female_penguin_weights = ____

# Iterate over the weight_log entries
for ____, ____, ____ in ____:
    # Check to see if species is already in the dictionary
    if ____ not in ____:
        # Create an empty list for any missing species
        female_penguin_weights[species] = ____
    # Append the sex and body_mass as a tuple to the species keys list
    female_penguin_weights[species].____
    
# Print the weights for 'Adlie'
print(____)
编辑并运行代码