首页 > 解决方案 > Difference of n dictionaries

问题描述

I'm looking for a way to determine the difference of n dictionaries in the following scenario: There are n dictionaries. Some of their keys match, but not all. Like this:

dict_a = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyC': 'valueC',
    'keyD': 'valueD',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}
dict_b = {
    'keyA': 'valueA',
    'keyB': 'valueB',
    'keyX': 'valueX',
    'keyD': 'valueH',
    'keyE': 'valueE',
    'keyF': 'valueF',
    'keyG': 'valueG'
}

I want to be able, to tell if the value of a key is different from the value of the same key in another dictionary. In the examble above keyD should be returned, because its value is different in dict_a and dict_b. keyX should not be returned, as it only occurs in dict_b This is relatively easy with only two dictionaries, but what is the best practise to accomplish this with n dictionaries?

标签: pythondictionary

解决方案


You can create this simple lambda function to do so:

>>> diff_keys = lambda x,y: [key for key in x.keys() if key in y.keys() and x[key] != y[key]]

>>> diff_keys(dict_a, dict_b)
['keyD']

And to handle n other dicts, you can create another function that can do so like this one:

>>> def get_different_keys(original_dict: dict, other_dicts: list):
...     different_keys = []
...     for dict_x in other_dicts:
...         different_keys.extend(diff_keys(original_dict, dict_x))
...         original_dict.update(dict_x)
...     return different_keys

>>> get_different_keys(dict_a, [dict_b]))
['keyD']

推荐阅读