python - 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?
解决方案
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']
推荐阅读
- python - 在函数名称上拆分 SQL 语句,但在 Python 中保留分隔符
- angularjs - 无法使用 angularjs 加载 fusioncharts
- windows - 创建一个 Oracle 钱包以在 Windows 上存储数据库凭证
- ios - 如何使用步进器增加标签值?
- mysql - 更新列以进行快速分析
- scala - 将 Map[String, Any] 转换为案例类的无形代码无法处理可选子结构
- html - 在浏览器中捕捉缩放
- oracle - 谁能告诉我 new 和 :new 之间的区别
- node.js - Javascript:评估UTC和中欧时间之间的增量
- c# - c# mstest测试查询数据库在读取配置时抛出FileNotFoundException的方法