Python:查找字典中的差异

标签 python dictionary

dictA = {'a':1, 'b':2, 'c':3}
dictB = {'a':2, 'b':2, 'c':4}

if dictA == dictB:
    print "dicts are same"
else:
    # print all the diffs
    for key in dictA.iterkeys():
        try:
            if dictA[key] != dictB[key]:
                print "different value for key: %s" % key
        except KeyError:
            print "dictB has no key: %s" % key

如果 dictA 和 dictB 中的项目数量很大,这会变得低效

还有更快的方法吗?

我正在考虑以某种方式使用集合,但不确定。

--

这可能是重复的,但人们似乎正在迭代其他类似问题的答案

最佳答案

您可以使用dict view objetcs :

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) Then these set operations are available (“other” refers either to another view or a set):

dictview & other
Return the intersection of the dictview and the other object as a new set.

dictview | other
Return the union of the dictview and the other object as a new set.

dictview - other
Return the difference between the dictview and the other object (all elements in dictview that aren’t in other) as a new set.

dictview ^ other
Return the symmetric difference (all elements either in dictview or other, but not in both) of the dictview and the other object as a new set.

diff = dictA.viewkeys() - dictB.viewkeys()

print(diff)   
set([])

print(dictA.viewitems() - dictB.viewitems())
set([('a', 1), ('c', 3)])

或设置:

print(set(dictA.iteritems()).difference(dictB.iteritems()))

你唯一的限制显然是内存

关于Python:查找字典中的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761207/

相关文章:

python - 在嵌入式 Python 解释器中跟踪代码执行

python - 如何遍历一行中的列以找到满足某些条件的第一个

python - 在 Python 和 wxpython 中使用 listctrl 对项目进行排序

python - 比较字典列表

python - 使用 lxml 在 python 中编码 - 复杂的解决方案

python - 拆分列表并存储在python中的字典中

javascript - 通过字典查找和替换,仅使用一次键

python - 使用相同的键将两本词典合二为一?

python-3.x - 词典列表

python - 如何计算最小长度的矩形数?