Python——移除具有匹配值的字典


當需要移除具有匹配值的字典時,要使用字典解析。

下面演示了同樣的程式碼 −

示例

 線上示例

my_dict_1 = [{'Hi': 32, "there": 32, "Will":19},{'Hi': 19, "there": 100, "Will": 13}, {'Hi': 72, "there": 19, "Will": 72}]

print("The first dictionary is : ")
print(my_dict_1)

my_dict_2 = [{'Hi': 72, "Will": 19}, {"Will": 13, "Hi": 19}]
print("The second dictionary is : ")
print(my_dict_2)

K = "Hi"
print("The value of K is ")
print(K)

temp = { element[K] for element in my_dict_2}

my_result = [element for element in my_dict_1 if element[K] not in temp]

print("The result is : " )
print(my_result)

輸出

The first dictionary is :
[{'Hi': 32, 'there': 32, 'Will': 19}, {'Hi': 19, 'there': 100, 'Will': 13}, {'Hi': 72, 'there': 19, 'Will': 72}]
The second dictionary is :
[{'Hi': 72, 'Will': 19}, {'Will': 13, 'Hi': 19}]
The value of K is
Hi
The result is :
[{'Hi': 32, 'there': 32, 'Will': 19}]

說明

  • 定義兩個字典並顯示在控制檯。

  • 定義一個 K 值並顯示在控制檯。

  • 迭代第二個字典,並檢查 K 的元素並存儲在臨時變數“temp”中。

  • 迭代第一個字典,並檢查其中的元素與臨時變數“temp”是否匹配並分配給變數。

  • 將此結果分配給變數。

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

更新於:06-09-2021

219 瀏覽

開啟你的 職業

完成課程獲取證書

開始
廣告
© . All rights reserved.