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”是否匹配並分配給變數。
將此結果分配給變數。
這是顯示在控制檯的輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP