gpt4 book ai didi

Python:发现字典中的差异

转载 作者:行者123 更新时间:2023-11-28 21:51:10 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com