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