เมื่อจำเป็นต้องจับคู่รายการค่าพจนานุกรมสองรายการ จะใช้เมธอด 'setdefault' และ 'extend'
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
my_dict_1 = {"Python" : [4, 7], "Fun" : [8, 6]}
my_dict_2 = {6 : [5, 7], 8 : [3, 6], 7 : [9, 8]}
print("The first dictionary is : " )
print(my_dict_1)
print("The second dictionary is : " )
print(my_dict_2)
sorted(my_dict_1.items(), key=lambda e: e[1][1])
print("The first dictionary after sorting is ")
print(my_dict_1)
sorted(my_dict_2.items(), key=lambda e: e[1][1])
print("The second dictionary after sorting is ")
print(my_dict_2)
my_result = {}
for key, value in my_dict_1.items():
for index in value:
my_result.setdefault(key, []).extend(my_dict_2.get(index, []))
print("The resultant dictionary is : ")
print(my_result) ผลลัพธ์
The first dictionary is :
{'Python': [4, 7], 'Fun': [8, 6]}
The second dictionary is :
{6: [5, 7], 8: [3, 6], 7: [9, 8]}
The first dictionary after sorting is
{'Python': [4, 7], 'Fun': [8, 6]}
The second dictionary after sorting is
{6: [5, 7], 8: [3, 6], 7: [9, 8]}
The resultant dictionary is :
{'Python': [9, 8], 'Fun': [3, 6, 5, 7]} คำอธิบาย
-
พจนานุกรมสองชุดถูกกำหนดและแสดงบนคอนโซล
-
มีการจัดเรียงโดยใช้วิธี 'จัดเรียง' และวิธีแลมบ์ดาและแสดงบนคอนโซล
-
พจนานุกรมว่างเปล่าถูกสร้างขึ้น
-
มีการวนซ้ำพจนานุกรม และคีย์ถูกตั้งค่าเป็นค่าเริ่มต้น
-
ดัชนีขององค์ประกอบในพจนานุกรมที่สองจะได้รับและเพิ่มลงในพจนานุกรมเปล่าโดยใช้วิธี 'ขยาย'
-
นี่คือเอาต์พุตที่แสดงบนคอนโซล