การเพิ่มและขยาย dictionary
หากต้องการเพิ่มข้อมูลลงใน dictionary สามารถสร้าง key ใหม่แล้วกำหนดค่าที่ต้องการได้เลย สิ่งสำคัญที่ควรจำคือ หากเป็น nested dictionary key ทุกตัวในเส้นทางต้องมีอยู่แล้ว และต้องกำหนดค่าทีละ key
นอกจากนี้ยังสามารถใช้เมธอด .update() เพื่ออัปเดต dictionary ด้วยชุด key และ value จาก dictionary อื่น, tuple หรือ keyword argument ได้
มี dictionary squirrels_by_park โหลดไว้ให้แล้ว โดยใช้ชื่อสวนสาธารณะเป็น key และค่าที่เก็บไว้คือ tuple ที่ประกอบด้วยสีหลัก, สีไฮไลต์, การกระทำ และปฏิกิริยาต่อมนุษย์
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ประเภทข้อมูลใน Python
คำแนะนำการฝึกหัด
- กำหนดรายการ
squirrels_madisonเป็น value ของ key'Madison Square Park'ใน dictionarysquirrels_by_park - อัปเดต key
'Union Square Park'ใน dictionarysquirrels_by_parkด้วยข้อมูลใน tuplesquirrels_union - วนลูปผ่าน dictionary
squirrels_by_park- แสดงผล
park_nameและรายการprimary_fur_colorทั้งหมดของกระรอกในสวนนั้น อย่างปลอดภัย โดยใช้ list comprehension และคืนค่า'N/A'หากไม่พบ key ดังกล่าว
- แสดงผล
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Assign squirrels_madison as the value to the 'Madison Square Park' key
____[____] = ____
# Update squirrels_by_park with the squirrels_union tuple
____.____([____])
# Loop over the park_name in the squirrels_by_park dictionary
for park_name in ____:
# Safely print a list of the primary_fur_color for each squirrel in park_name
print(park_name, [____.get('____', '____') for squirrel in ____[____]])