[英]Comparing Keys and Values in 2 Dictionaries
我想取一個字典中填充的聚合數字,並將鍵和值與另一個字典中的鍵和值進行比較,以確定兩者之間的差異。 我只能得出如下結論:
for i in res.keys():
if res2.get(i):
print 'match',i
else:
print i,'does not match'
for i in res2.keys():
if res.get(i):
print 'match',i
else:
print i,'does not match'
for i in res.values():
if res2.get(i):
print 'match',i
else:
print i,'does not match'
for i in res2.values():
if res.get(i):
print 'match',i
else:
print i,'does not match'
麻煩和馬車......需要幫助!
我不確定你的第二對循環是怎么做的。 也許這就是你所說的“and buggy”,因為他們正在檢查一個字典中的值是另一個中的鍵。
這將檢查兩個dicts是否包含相同鍵的相同值。 通過構造鍵的並集可以避免循環兩次,然后有4種情況要處理(而不是8)。
for key in set(res.keys()).union(res2.keys()):
if key not in res:
print "res doesn't contain", key
elif key not in res2:
print "res2 doesn't contain", key
elif res[key] == res2[key]:
print "match", key
else:
print "don't match", key
聽起來像使用一組功能可能會有用。 與Ned Batchelder相似:
fruit_available = {'apples': 25, 'oranges': 0, 'mango': 12, 'pineapple': 0 }
my_satchel = {'apples': 1, 'oranges': 0, 'kiwi': 13 }
available = set(fruit_available.keys())
satchel = set(my_satchel.keys())
# fruit not in your satchel, but that is available
print available.difference(satchel)
我不完全確定你的意思是匹配鍵和值,但這是最簡單的:
a_not_b_keys = set(a.keys()) - set(b.keys())
a_not_b_values = set(a.values()) - set(b.values())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.