เมื่อต้องการกลับค่า (inverse) ของ dictionary ที่มี value เป็นลิสต์ ให้กลายเป็น dictionary ใหม่ที่ key คือค่าเดิม และ value เป็นลิสต์ของ key เดิม สามารถใช้ defaultdict ได้
ตัวอย่าง
from collections import defaultdict
my_dict = {13: [12, 23], 22: [31], 34: [21], 44: [52, 31]}
print("The dictionary is :")
print(my_dict)
my_result = defaultdict(list)
for keys, values in my_dict.items():
for val in values:
my_result[val].append(keys)
print("The result is :")
print(dict(my_result))
ผลลัพธ์
The dictionary is : {34: [21], 44: [52, 31], 13: [12, 23], 22: [31]}
The result is : {52: [44], 31: [44, 22], 12: [13], 21: [34], 23: [13]}
คำอธิบาย
นำเข้า
defaultdictจากcollectionsกำหนด dictionary ที่ value เป็นลิสต์ แสดงผล
สร้าง
defaultdict(list)สำหรับผลลัพธ์วนลูป
items()ของ dictionary เดิม วนลูปในแต่ละ value list ใช้ค่าเป็น key ใหม่ append key เดิมเข้าไปแปลงกลับเป็น dict ธรรมดาแสดงผล