Python - 兩個詞典值列表的交叉對映


要交叉對映兩個詞典值列表,可以使用“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]}

說明

  • 定義了兩個詞典,並在控制檯上顯示。

  • 使用“sorted”方法和lambda方法對它們進行排序,並顯示在控制檯上。

  • 建立了一個空詞典。

  • 對詞典進行迭代,並將關鍵字設定為預設值。

  • 獲取第二個詞典中元素的索引,並使用“extend”方法將其新增到空詞典中。

  • 這是在控制檯上顯示的輸出。

更新於: 2021-09-13

536 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

開始
廣告