【问题标题】:How to compare two dict and check if there is new item如何比较两个字典并检查是否有新项目
【发布时间】:2018-05-22 18:46:05
【问题描述】:

如何比较两个dict并检查是否有新项目,例如在第二个dict中有CCC,如何比较并获取新变量中的CCC。

dict1 = {'AAA': '0.23444', 'BBB': '0.5343'}
dict2 = {'AAA': '0.34343', 'BBB': '0.3435', 'CCC': '0.53322'}

【问题讨论】:

  • “在新变量中”是什么意思?一本新词典?

标签: python python-3.x python-2.7 dictionary


【解决方案1】:

要查找dict2 中没有出现在dict1 中的键,可以使用差异:

res = dict2.keys() - dict1.keys()

{'CCC'}

然后您可以通过此集合访问键值组合:

res_d = {k: dict2[k] for k in res}

{'CCC': '0.53322'}

注意,在 Python 3 中,dict.keys() 是一个可以直接使用的视图,就像它是一个集合一样,这就是为什么不需要转换为set

您还可以使用字典推导来组合这些步骤:

res_d = {k: dict2[k] for k in dict2.keys() - dict1.keys()}

【讨论】:

  • 作为附加说明,您可以使用 symmetric_difference 来查找加法和减法。
【解决方案2】:
'''
OP wants to compare too dicts. If there is a different (new) key in one of the
dicts, he wants to add that value to dict1
'''

dict1 = {'AAA': '0.23444', 'BBB': '0.5343'}
dict2 = {'AAA': '0.34343', 'BBB': '0.3435', 'CCC': '0.53322'}

for key, value in dict2.items():
   if key not in dict1:
      dict1[key] = value

print(dict1)

我们可以遍历第二个dict中的每个key,如果没有出现在第一个dict中,我们可以在最后添加。这是输出:

{'AAA': '0.23444', 'BBB': '0.5343', 'CCC': '0.53322'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多