安全地向键的值列表追加元素
在处理字典时,您常常需要先初始化某种数据类型才能使用它。一个典型的例子是列表:必须在每个键上先初始化列表,之后才能向该列表追加元素。
defaultdict 允许您预先定义每个尚未初始化的键将包含什么。在创建 defaultdict 时,传入您希望的类型,例如 list、tuple、set、int、string、dictionary 或其他任何有效的类型对象。
本题将继续使用上一练习中的体重记录,但这次是研究中的雄性企鹅。
本练习是课程的一部分
Python 的数据类型
练习说明
- 从
collections导入defaultdict。 - 创建一个默认类型为
list的defaultdict,命名为male_penguin_weights。 - 遍历列表
weight_log,将其解包到变量species、sex和body_mass(与上一练习相同)。使用species作为male_penguin_weights字典的键,并将body_mass追加到其对应的值中。 - 打印
male_penguin_weights字典的前 2 个条目。可以使用.items()方法,并记得先将其转换为列表。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import defaultdict
____
# Create a defaultdict with a default type of list: male_penguin_weights
male_penguin_weights = ____
# Iterate over the weight_log entries
for ____, ____, ____ in ____:
# Use the species as the key, and append the body_mass to it
____
# Print the first 2 items of the male_penguin_weights dictionary
print(____(____)[:2])