การเพิ่มข้อมูลลงใน value list ของ key อย่างปลอดภัย
เวลาทำงานกับ dictionary มักต้องกำหนดค่าเริ่มต้นของประเภทข้อมูลก่อนจึงจะใช้งานได้ ตัวอย่างที่ชัดเจนคือ list ซึ่งต้องกำหนดค่าเริ่มต้นในแต่ละ key ก่อนจึงจะ append ได้
defaultdict ช่วยให้กำหนดได้ว่า key ที่ยังไม่มีค่าเริ่มต้นจะเก็บข้อมูลประเภทใด เมื่อสร้าง defaultdict ให้ระบุประเภทที่ต้องการ เช่น list, tuple, set, int, string, dictionary หรือประเภทออบเจกต์ที่ถูกต้องอื่น ๆ
ในแบบฝึกหัดนี้จะใช้ไฟล์บันทึกน้ำหนักชุดเดิมกับแบบฝึกหัดที่แล้ว แต่เปลี่ยนมาทำงานกับข้อมูลของเพนกวินเพศผู้แทน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ประเภทข้อมูลใน Python
คำแนะนำการฝึกหัด
- นำเข้า
defaultdictจากcollections - สร้าง
defaultdictที่มีประเภทค่าเริ่มต้นเป็นlistชื่อว่าmale_penguin_weights - วนซ้ำผ่าน list
weight_logโดย unpack เป็นตัวแปรspecies,sexและbody_massเช่นเดียวกับแบบฝึกหัดที่แล้ว ใช้speciesเป็น key ของ dictionarymale_penguin_weightsและ appendbody_massเข้าไปใน value - แสดง 2 รายการแรกของ dictionary
male_penguin_weightsโดยใช้เมธอด.items()อย่าลืมแปลงเป็น list ก่อน
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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])