python - 计算两个 Python 字典中包含的键的差异

标签 python dictionary

假设我有两个 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'必须添加到字典中。 键值没有固定格式。它可以是一个简单的值,也可以是一个字典或字典的字典。

最佳答案

您可以对键使用 set 操作:

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

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

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])

这是一些示例输出:

>>> 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'])

作为 github 存储库提供: https://github.com/hughdbrown/dictdiffer

关于python - 计算两个 Python 字典中包含的键的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1165352/

相关文章:

python - 如何将 numpy 数组中的图像读入 PIL 图像?

python - Bokeh 服务器 - 在回调返回之前强制刷新客户端图形?

python ,scikits-学习 : which learning methods support sparse feature vectors?

python - 如何在 pygtk 中使用同一个小部件两次?

python - 来自 mysql 数据库的 dict 元组的元组

python - 使用计数器合并字典

python - Pyserial:如何在打开串行端口之前知道它是否空闲

c# - 如何将 IEnumerable 转换为字典

python - 向字典添加元素会破坏编码

c++ - 类 A 的 boost ptr_map 作为键和指针 vector 作为值 B 的内存消耗