简体   繁体   English

如何比较两个不同字典中相同键的值

[英]How to compare values of same keys in two separate dictionaries

I'm sure this has been asked, my apologies for the duplication but I can't find an answer.我确定有人问过这个问题,我为重复表示歉意,但我找不到答案。 I need to compare two dictionaries containing the same keys but separate values (inventory management with thousands of items).我需要比较两个包含相同键但不同值的字典(包含数千个项目的库存管理)。 I can find pairs, which is helpful, but I need an expression that returns the value of a key in dictionary B when it is lower than the same key in dictionary A. Here is what I have so far:我可以找到对,这很有用,但我需要一个表达式,当它低于字典 A 中的相同键时,它返回字典 B 中键的值。这是我目前所拥有的:

dictionary1 = {'A':7, 'B':8, 'C':9}

dictionary2 = {'A':2, 'B':8, 'C':22}

pairs = dict()

for key in dictionary1:
    if key in dictionary2 and dictionary1[key] ==dictionary2[key]:

        pairs[key] = dictionary1[key]

print(pairs)

{'B': 8}

Process finished with exit code 0

You might want to take a look at deepdiff.DeepDiff to find any changes in your dictionary (even on multiple levels):您可能想查看deepdiff.DeepDiff以查找字典中的任何更改(甚至在多个级别上):

from deepdiff import DeepDiff
dict_a = {'A':7, 'B':8, 'C':9}
dict_b = {'A':2, 'B':8, 'C':22}
dd = DeepDiff(dict_a, dict_b)

output: output:

{'values_changed': {"root['A']": {'new_value': 2, 'old_value': 7}, "root['C']": {'new_value': 22, 'old_value': 9}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何比较具有相同键的两个字典并使用 python 中的条件更新值? - How to compare two dictionaries with the same keys and update values with a condition in python? 比较两个字典的键和值 - compare two dictionaries' keys and values 如何比较具有相同键的两个嵌套字典并使用 python 中的条件更新值? - How to compare two nested dictionaries with the same keys and update values with a condition in python? 如何比较 python 中具有不同键的两个字典的值 - How to compare values of two dictionaries that have different keys in python 如何比较具有不同键但相似值的两个字典并删除重复项 - how to compare two dictionaries with different keys but similar values and delete the duplicates 比较两个字典中的键并使用 for 循环更新值 - compare keys in two dictionaries and update values with for loops 如何在 python 中组合(附加值)两个具有相同键的嵌套字典? - How to combine (append values) two nested dictionaries with the same keys in python? 如何使用两个词典中的列表中的相同键来收集值 - How to collect values with the same keys in a list from the two dictionaries 如何在Python中比较两个不同字典的键? - How to compare keys of two different dictionaries in Python? 合并两个具有相同键和不同值的字典 - Consolidating two dictionaries with the same keys and different values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM