gpt4 book ai didi

python - 使用 python 比较字典

转载 作者:太空宇宙 更新时间:2023-11-04 03:41:47 24 4
gpt4 key购买 nike

我必须在 python 中比较 2 个字典。例如,我使用了下面的代码,如果 di1 和 di2 中键:值对的数量相同,则它工作正常,但如果 di2 中缺少键:值对,则代码失败。

di1 = {'Name': 'cat', 'Age': 9,'Alpha':'mat','Beta':'deep'};
di2 = {'Name': 'cat', 'Age': 27,'Alpha':'rat'};
dicdiff = [k for k in di1 if di1[k] != di2[k]]
for k in dicdiff:
print k, ':', di1[k], '->', di2[k]

最佳答案

使用dictionary view objects并使用集合操作:

for key, value in di1.viewitems() ^ di2.viewitems():
print '{!r}: {!r}'.format(key, value)

^ 给出了两个字典之间的对称差异;这将列出两个字典中存在但另一个字典中缺失的键,不同的值。

这会产生:

>>> di1 = {'Name': 'cat', 'Age': 9,'Alpha':'mat','Beta':'deep'};
>>> di2 = {'Name': 'cat', 'Age': 27,'Alpha':'rat'};
>>> for key, value in di1.viewitems() ^ di2.viewitems():
... print '{!r}: {!r}'.format(key, value)
...
'Alpha': 'rat'
'Alpha': 'mat'
'Beta': 'deep'
'Age': 27
'Age': 9

您可以通过仅查看一个或另一个字典中的键来进一步完善它:

print 'Added keys'
for key in di2.viewkeys() - di1.viewkeys():
print '{!r}: {!r}'.format(key, di2[key])

print 'Removed keys'
for key in di1.viewkeys() - di2.viewkeys():
print '{!r}: {!r}'.format(key, di1[key])

print 'Changed keys'
for key in di1.viewkeys() & di2.viewkeys():
if di1[key] != di2[key]:
print '{!r}: {!r} -> {!r}'.format(key, di1[key], di2[key])

这会产生:

>>> print 'Added keys'
Added keys
>>> for key in di2.viewkeys() - di1.viewkeys():
... print '{!r}: {!r}'.format(key, di2[key])
...
>>> print 'Removed keys'
Removed keys
>>> for key in di1.viewkeys() - di2.viewkeys():
... print '{!r}: {!r}'.format(key, di1[key])
...
'Beta': 'deep'
>>> print 'Changed keys'
Changed keys
>>> for key in di1.viewkeys() & di2.viewkeys():
... if di1[key] != di2[key]:
... print '{!r}: {!r} -> {!r}'.format(key, di1[key], di2[key])
...
'Alpha': 'mat' -> 'rat'
'Age': 9 -> 27

关于python - 使用 python 比较字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26098614/

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