Python – 删除具有匹配值的字典
pythonserver side programmingprogramming更新于 2025/10/14 3:24:17
当需要删除具有匹配值的字典时,会使用字典推导。
下面是相同的演示 −
示例
my_dict_1 = [{'Hi': 32, "there": 32, "Will":19},{'Hi': 19, "there": 100, "Will": 13}, {'Hi': 72, "there": 19, "Will": 72}]
print("第一个字典是:")
print(my_dict_1)
my_dict_2 = [{"Hi": 72, "Will": 19}, {"Will": 13, "Hi": 19}]
print("第二个字典是:")
print(my_dict_2)
K = "Hi"
print("K 的值为 ")
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("结果为: " )
print(my_result)
输出
第一个字典是:
[{'Hi': 32, 'there': 32, 'Will': 19}, {'Hi': 19, 'there': 100, 'Will': 13}, {'Hi': 72, 'there': 19, 'Will': 72}]
第二个字典为:
[{'Hi': 72, 'Will': 19}, {'Will': 13, 'Hi': 19}]
K 的值为
Hi
结果为:
[{'Hi': 32, 'there': 32, 'Will': 19}]
解释
定义了两个字典,并在控制台上显示。
定义了 K 的值,并在控制台上显示。
第二个字典被迭代,元素用 K 检查并存储在临时变量‘temp’。
第一个字典被迭代,其中的元素用临时变量‘temp’检查并分配给一个变量。
这个结果被分配给一个变量。
这是控制台上显示的输出。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

