如何获得Python中两个字典之间的差异? [英] How to get the difference between two dictionaries in Python?

查看:52
本文介绍了如何获得Python中两个字典之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两本字典,我需要找出两者之间的区别,这应该给我一个键和一个值.

I have two dictionaries, and I need to find the difference between the two, which should give me both a key and a value.

我搜索并找到了一些插件/包,例如 datadiff 和 dictdiff-master,但是当我尝试在 Python 2.7 中导入它们时,它说没有定义此类模块.

I have searched and found some addons/packages like datadiff and dictdiff-master, but when I try to import them in Python 2.7, it says that no such modules are defined.

我在这里使用了一套:

first_dict = {}
second_dict = {}
 
value = set(second_dict) - set(first_dict)
print value

我的输出是:

>>> set(['SCD-3547', 'SCD-3456'])

我只得到键,我还需要得到值.

I am getting only keys, and I need to also get the values.

推荐答案

尝试以下代码片段,使用字典理解:

Try the following snippet, using a dictionary comprehension:

value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

在上面的代码中,我们找到键的不同,然后重建一个dict取相应的值.

In the above code we find the difference of the keys and then rebuild a dict taking the corresponding values.

这篇关于如何获得Python中两个字典之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆