如何比较包含词典的词典?
这将适用于字典包含简单值
的情况# will show the keys with different values
d1_keys = set(dict1.keys())
d2_keys = set(dict2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
modified = {}
for i in intersect_keys:
if dict1[i] != dict2[i] : modified.update({i : (dict1[i], dict2[i])})
但我有这样的字典:
{ 'medic1' : {'date' : '02/02/2015', 'no' : '123' }, 'medic2' : {'date' :'02/03/2015', 'no' : '456' }}
答案 0 :(得分:3)
通过嵌套字典的递归函数。
keys()
和set operation.
for
循环迭代常用密钥。type
是否为dict
。dict
,则调用相同的函数并将值字典作为参数传递。并将结果作为键添加到modified
字典中。 modified
字典中。 代码:
dict1 = {
'medic1' : {'date' : '02/02/2015', 'no' : '123' },
'medic2' : {'date' : '02/03/2015', 'no' : '456' },
'testkey1': 'testvalue1',
'testkey2': 'testvalue2',
'testkey3':{ "level2_1":"value2_1",
"level2_2":{
"level3_1": "value3_1_change",
"level3_2": "value3_2",
}
}
}
dict2 = {
'medic1' : {'date' : '02/02/2015', 'no' : '456' },
'medic2' : {'date' : '02/03/2015', 'no' : '456' },
'testkey1': 'testvalue1',
'testkey2': 'testvalue22',
'testkey3':{ "level2_1":"value2_1",
"level2_2":{
"level3_1": "value3_1",
"level3_2": "value3_2",
}
}
}
import copy
def compareDict(dict1, dict2):
d1_keys = dict1.keys()
d2_keys = dict2.keys()
intersect_keys = set(d1_keys).intersection(set(d2_keys))
modified = {}
for i in intersect_keys:
if dict1[i] != dict2[i] :
if isinstance(dict1[i], dict) and isinstance(dict1[i], dict):
modified[i]=compareDict(dict1[i], dict2[i])
else:
modified.update({i : (dict1[i], dict2[i])})
return copy.deepcopy(modified)
modified = compareDict(dict1, dict2)
import pprint
pprint.pprint(modified)
输出:
vivek@vivek:~/Desktop/stackoverflow$ python 5.py
{'medic1': {'no': ('123', '456')},
'testkey2': ('testvalue2', 'testvalue22'),
'testkey3': {'level2_2': {'level3_1': ('value3_1_change', 'value3_1')}}}
答案 1 :(得分:0)
只要键可以播放(dict
保证! - )值是否重要并不重要 - - 代码如:
common_keys = set(dict1).intersection(dict2)
(前三行的简化版),然后
modified = {k: (dict1[k], dict2[k])
for k in common_keys if dict1[k] != dict2[k]}
(最近三行的简化版)可以正常使用!