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

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

问题描述

我有两个字典。我需要找到两者之间的区别,这应该给我键和值。

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

我已经搜索并找到了一些插件/软件包,例如datadiff,dictdiff-master,但是当我在Python 2.7中尝试过,它说没有定义这样的模块。

I have searched and found some addons/packages like datadiff, dictdiff-master but when I try it in Python 2.7 it says no such module defined.

我在这里使用set。

I used set here.

first_dict = {}
second_dict = {}

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

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

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

我只获得密钥,甚至需要获取值。

I am getting only key, I need to even 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) }

In上面的代码我们找到键的差异 ,然后使用相应的值重建 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天全站免登陆