假设您有 2 个字典,
A
和 B
,其键可以相同,但值(整数)不同。如何比较两个字典,以便如果键匹配,您将得到差异(例如,如果 x
是键 "A"
中的值,而 y
是键 "B"
中的值,那么结果应该是 x-y
)作为结果(最好作为新字典)之间的两个字典。
理想情况下,您还可以比较百分比增益(两个字典之间的值按百分比变化了多少,这是特定时间的数字快照)。
给定两个字典,
A
和B
,它们可能/可能不具有相同的键,您可以这样做:
A = {'a':5, 't':4, 'd':2}
B = {'s':11, 'a':4, 'd': 0}
C = {x: A[x] - B[x] for x in A if x in B}
仅减去 both 字典中相同的键。
您可以使用
dict
理解来循环遍历键,然后从每个原始 dict
中减去相应的值。
>>> a = {'a': 5, 'b': 3, 'c': 12}
>>> b = {'a': 1, 'b': 7, 'c': 19}
>>> {k: b[k] - a[k] for k in a}
{'a': -4, 'b': 4, 'c': 7}
这假设两个
dict
具有完全相同的键。否则,您必须考虑如果一个 dict
有键但另一个没有(也许是一些默认值?),您期望什么行为
否则,如果您只想评估共享密钥,则可以使用密钥的集合交集
>>> {k: b[k] - a[k] for k in a.keys() & b.keys()}
{'a': -4, 'b': 4, 'c': 7}
def difference_dict(Dict_A, Dict_B):
output_dict = {}
for key in Dict_A.keys():
if key in Dict_B.keys():
output_dict[key] = abs(Dict_A[key] - Dict_B[key])
return output_dict
>>> Dict_A = {'a': 4, 'b': 3, 'c':7}
>>> Dict_B = {'a': 3, 'c': 23, 'd': 2}
>>> Diff = difference_dict(Dict_A, Dict_B)
>>> Diff
{'a': 1, 'c': 16}
如果你想将所有内容都放在一行中,那就是......
def difference_dict(Dict_A, Dict_B):
output_dict = {key: abs(Dict_A[key] - Dict_B[key]) for key in Dict_A.keys() if key in Dict_B.keys()}
return output_dict
如果你想将相似键的差异放入新字典中,你可以执行如下操作:
new_dict={}
for key in A:
if key in B:
new_dict[key] = A[key] - B[key]
...我们可以将其放入一行
new_dict = { key : A[key] - B[key] for key in A if key in B }
这里有一个适用于这种情况的Python包:
https://dictdiffer.readthedocs.io/en/latest/
from dictdiffer import diff
print(list(diff(a, b)))
就可以了。
你显然必须与任何深度进行比较。您的错误/差异消息还必须准确地显示我们正在讨论的
dict
中的位置。递归解决方案是最明显的一种。无需外包装。
这对于测试目的可能有用。
def diff_dicts(expected_dict, found_dict, depth=0, key_trail=[]):
for key, expected_value in expected_dict.items():
key_trail.append(key)
if key in found_dict:
found_value = found_dict[key]
if found_value != expected_value:
if isinstance(expected_value, dict) and isinstance(found_value, dict):
diff_dicts(expected_value, found_value, depth=depth+1, key_trail=key_trail)
else:
logger.error(f"""difference for key {key} depth {depth}:
expected of type {type(expected_value)}: {expected_value}
found of type {type(found_value)}: {found_value}
key trail: {key_trail}""")
else:
logger.error(f'no key "{key}" in found_dict depth {depth}:\n{found_dict}\nkey trail: {key_trail}')
key_trail.pop()
diff_dicts(expected_data, used_data)
输出示例:
ERROR doc_indexer:test_run_search.py:549 difference for key fields depth 2:
expected of type <class 'list'>: ['spanish_normalised_content.spanish_stemmed']
found of type <class 'list'>: ['english_normalised_content.english_stemmed']
key trail: ['query', 'simple_query_string', 'fields']
ERROR doc_indexer:test_run_search.py:554 no key "spanish_normalised_content.spanish_stemmed" in found_dict depth 2:
{'english_normalised_content.english_stemmed': {'matched_fields': ['english_normalised_content.english_stemmed'], 'type': 'fvh'}}
key trail: ['highlight', 'fields', 'spanish_normalised_content.spanish_stemmed']