Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何扩展字典以合并所有匹配值?_Python_Dictionary - Fatal编程技术网

Python 如何扩展字典以合并所有匹配值?

Python 如何扩展字典以合并所有匹配值?,python,dictionary,Python,Dictionary,我有一本这样的词典: { 'key1': [1,2,3], 'key2': [4,5,6], '1': [4,5], '4': [4,6] } 现在,我需要解包这个字典,这样所有作为键出现的值都会附加到原始键上。我的意思是,结果应该是: { 'key1': [1,2,3,4,5,6], 'key2': [4,5,6] '1': [4,5,6] '4': [4,6] } 基本上,key1中的1值在{'1':[4,5,6]}中有一个

我有一本这样的词典:

{
    'key1': [1,2,3],
    'key2': [4,5,6],
    '1': [4,5],
    '4': [4,6]
}
现在,我需要解包这个字典,这样所有作为键出现的值都会附加到原始键上。我的意思是,结果应该是:

{
    'key1': [1,2,3,4,5,6],
    'key2': [4,5,6]
    '1': [4,5,6]
    '4': [4,6]
}
基本上,key1中的1值在{'1':[4,5,6]}中有一个键值对。所以我需要把它附加到原始键1上。然后,4也有一个对应的键值对,因此也应该附加到key1,因为key1现在有4

注意,我不知道这本词典的“深度”。因此,我需要一个可扩展到任意深度的解决方案

到目前为止,我已经尝试过:

new_dict = {}
def expand(dict):
    for k in dict:
        for dep in dict[k]:
            val = dict.get(dep)
            new_dict[k] = [dep, val]
    return new_dict

但这个解决方案只能达到两个深度。我不知道如何在任意深度捕获更多匹配的键。

您可以使用
while
循环不断扩展dict的每个子列表,其中包含与旧子列表中不包含的项匹配的键中的项。使用集合有效地获取此类增量:

def expand(d):
    for lst in d.values():
        old = set()
        new = set(lst)
        while True:
            delta = new - old
            if not delta:
                break
            old = new.copy()
            for i in map(str, delta):
                if i in d:
                    new.update(d[i])
        lst[:] = new
    return d
因此,如果将示例输入作为变量
d
expand(d)
返回:

{'key1': [1, 2, 3, 4, 5, 6], 'key2': [4, 5, 6], '1': [4, 5, 6], '4': [4, 6]}

您当前的尝试有什么错误?我看不到你的密码…很抱歉。刚刚更新了我的帖子,展示了我迄今为止所做的尝试。