如果键值对与另一个字典中的键值对相同,如何删除整个字典

2024-06-01 06:49:28 发布

您现在位置:Python中文网/ 问答频道 /正文

如果字典中的一个值与另一个字典中的值相同,你们将如何创建一个脚本来删除整个字典

dict_1 = {'_id': {'$oid': 'hi'}, 'navigator': {'CodeName': 'Web', 'appName': 'Netscape'}}
dict_2 = {'_id': {'$oid': 'bye'}, 'navigator': {'CodeName': 'Web', 'appName': 'Netscape'}}
dict_3 = {'_id': {'$oid': 'hello'}, 'navigator': {'Name': 'Fire', 'Name': 'scape'}}

list_dict = [dict_1, dict_2, dict_3]

因为dict_1和dict_2都有'navigator': {'CodeName': 'Web', 'appName': 'Netscape'}},所以我只想要其中一个。所以我想删除其中一本词典,保留另一本

我希望我的输出是:

[{'_id': {'$oid': 'hi'}, 'navigator': {'CodeName': 'Web', 'appName': 'Netscape'}}, {'_id': {'$oid': 'hello'}, 'navigator': {'Name': 'Fire', 'Name': 'scape'}}]
# [dict_1, dict_3]

Tags: name脚本webidnavigatorhello字典hi
2条回答

为了提供答案,我需要你的问题的更多细节:

  1. 什么是dict 1?存在语法错误,因为变量不能是数字
  2. 你的问题不清楚,在b相同且相同的情况下,应该保留哪一个
  3. a和b已使用但未声明

可以使用del dict_name删除词典

dict1 = {'a': 1, 'b': 2}
del dict1

假设字典的名称总是dict_n,其中n的范围从1到字典的数量,下面是答案

另外,假设您只对b的唯一值感兴趣,下面的代码应该可以工作

代码:

dict_1 = {'a': 1, 'b': 2}
dict_2 = {'a': 2, 'b': 2}
dict_3 = {'a': 3, 'b': 3}
dict_4 = {'a': 4, 'b': 4}

list_of_dicts = [dict_1,dict_2,dict_3,dict_4]
vals_of_dicts = [list(d.values())[1] for d in list_of_dicts]
x = ['dict '+str(i+1) for i,v in enumerate(vals_of_dicts) if v not in vals_of_dicts[:i]]
print (x)

其输出将为:

['dict 1', 'dict 3', 'dict 4']

但是,如果确实要从原始列表中删除词典本身,则可以将x = [....]代码替换为:

[list_of_dicts.pop(i) for i,v in enumerate(vals_of_dicts) if v in vals_of_dicts[:i]]
print (list_of_dicts)

不需要分配给x

这将在b中打印出实际的字典,而不包含重复的值:

[{'a': 1, 'b': 2}, {'a': 3, 'b': 3}, {'a': 4, 'b': 4}]

相关问题 更多 >