这对你有用吗?请注意,由于字典中元素的顺序是任意的,因此您不能保证最终会将哪些键插入到输出字典中。
dict_out = {}
processed = set()
for k1, v1 in dict_in.items():
if k1 not in processed:
processed.add(k1)
vo = v1
for k2, v2 in dict_in.items():
if k2 not in processed and set(v1) & set(v2):
vo = sorted(list(set(vo + v2)))
processed.add(k2)
dict_out[k1] = vo
这对于:
dict_in = {'key1': ['1', '2', '3'], 'key2': ['3', '4', '5'], 'key3': ['6', '7', '8']}
给出:
{'key1': {'1', '2', '3', '4', '5'}, 'key3': ['6', '7', '8']}
对于:
dict_in = {'key1': ['1', '2', '3'], 'key2': ['3', '4', '5'],
'key3': ['6', '7', '8'], 'key4': ['7', '9']}
给出:
{'key1': {'1', '2', '3', '4', '5'}, 'key3': {'6', '7', '8', '9'}}
最后,对于:
dict_in = {'key1': ['1', '2', '3'], 'key2': ['3', '4', '5'],
'key3': ['6', '7', '8'], 'key4': ['5', '6', '7']}
它给:
{'key1': {'1', '2', '3', '4', '5'}, 'key3': {'5', '6', '7', '8'}}
编辑
OP 要求即使合并的结果也应该相互合并。为此,我们可以将上面的代码包装在一个循环中,如下所示:
d = dict_in
processed = set([None])
while processed:
dict_out = {}
processed = set()
for k1, v1 in d.items():
if k1 not in processed:
vo = v1
for k2, v2 in d.items():
if k1 is not k2 and set(vo) & set(v2):
vo = sorted(list(set(vo + v2)))
processed.add(k2)
dict_out[k1] = vo
d = dict_out
然后,对于:
dict_in = {'key1': ['1', '2', '3'], 'key2': ['3', '4', '5'],
'key3': ['6', '7', '8'], 'key4': ['5', '6', '7']}
我们得到:
{'key4': ['1', '2', '3', '4', '5', '6', '7', '8']}
并为:
dict_in = {'key1': ['1', '2', '3'], 'key2': ['3', '4', '5'],
'key3': ['4', '6', '7'], 'key4': ['8', '9']}
我们得到:
{'key1': ['1', '2', '3', '4', '5', '6', '7'], 'key4': ['8', '9']}