计算两个 Python 字典中包含的键的差异 [英] Calculate difference in keys contained in two Python dictionaries

查看:22
本文介绍了计算两个 Python 字典中包含的键的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个 Python 词典 - dictAdictB.我需要找出 dictB 中是否存在任何键,但 dictA 中没有.最快的方法是什么?

我应该将字典键转换成一个集合然后再去吗?

有兴趣了解您的想法...

<小时>

感谢您的回复.

抱歉没有正确说明我的问题.我的场景是这样的 - 我有一个 dictA,它可以与 dictB 相同,或者与 dictB 相比可能缺少一些键,否则某些键的值可能不同,必须设置为 dictA 键的值.

问题是字典没有标准,可以有可以是dict的dict的值.

dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}......

因此必须将key2"值重置为新值,并且必须将key13"添加到字典中.键值没有固定格式.它可以是一个简单的值,也可以是一个 dict 或一个 dict 的 dict.

解决方案

您可以对键使用 set 操作:

diff = set(dictb.keys()) - set(dicta.keys())

这是一个查找所有可能性的类:添加了什么,删除了什么,哪些键值对相同​​,哪些键值对发生了变化.

class DictDiffer(object):"""计算两个字典之间的差异为:(1) 添加的项目(2) 删除的项目(3) 两者中的键相同但值已更改(4) 键值相同且值不变"""def __init__(self, current_dict, past_dict):self.current_dict, self.past_dict = current_dict, past_dictself.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())self.intersect = self.set_current.intersection(self.set_past)定义添加(自己):返回 self.set_current - self.intersectdef 移除(自我):返回 self.set_past - self.intersectdef改变(自我):return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])定义不变(自我):return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])

这是一些示例输出:

<预><代码>>>>a = {'a':1,'b':1,'c':0}>>>b = {'a':1,'b':2,'d':0}>>>d = DictDiffer(b, a)>>>打印添加:",d. added()添加:设置(['d'])>>>打印已删除:",d.removed()移除:set(['c'])>>>打印更改:",d.changed()更改:设置(['b'])>>>打印不变:",d.unchanged()不变:set(['a'])

可作为 github 存储库使用:https://github.com/hughdbrown/dictdiffer

Suppose I have two Python dictionaries - dictA and dictB. I need to find out if there are any keys which are present in dictB but not in dictA. What is the fastest way to go about it?

Should I convert the dictionary keys into a set and then go about?

Interested in knowing your thoughts...


Thanks for your responses.

Apologies for not stating my question properly. My scenario is like this - I have a dictA which can be the same as dictB or may have some keys missing as compared to dictB or else the value of some keys might be different which has to be set to that of dictA key's value.

Problem is the dictionary has no standard and can have values which can be dict of dict.

Say

dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......

So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict. The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.

解决方案

You can use set operations on the keys:

diff = set(dictb.keys()) - set(dicta.keys())

Here is a class to find all the possibilities: what was added, what was removed, which key-value pairs are the same, and which key-value pairs are changed.

class DictDiffer(object):
    """
    Calculate the difference between two dictionaries as:
    (1) items added
    (2) items removed
    (3) keys same in both but changed values
    (4) keys same in both and unchanged values
    """
    def __init__(self, current_dict, past_dict):
        self.current_dict, self.past_dict = current_dict, past_dict
        self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
        self.intersect = self.set_current.intersection(self.set_past)
    def added(self):
        return self.set_current - self.intersect 
    def removed(self):
        return self.set_past - self.intersect 
    def changed(self):
        return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
    def unchanged(self):
        return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])

Here is some sample output:

>>> a = {'a': 1, 'b': 1, 'c': 0}
>>> b = {'a': 1, 'b': 2, 'd': 0}
>>> d = DictDiffer(b, a)
>>> print "Added:", d.added()
Added: set(['d'])
>>> print "Removed:", d.removed()
Removed: set(['c'])
>>> print "Changed:", d.changed()
Changed: set(['b'])
>>> print "Unchanged:", d.unchanged()
Unchanged: set(['a'])

Available as a github repo: https://github.com/hughdbrown/dictdiffer

这篇关于计算两个 Python 字典中包含的键的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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