将表示图形的字典展平为列表字典

Flattening a dictionary representing a graph into a dictionary of lists

我有一个字典,它表示一个图形,如下所示:

{
   '1': ['2', '3', '4'],
   '2': ['5', '6', '7'],
   '3': ['8', '9', '10'],
}

我想 "flatten" 这样我就可以得到这样的结果:

{
 '1': {
     '2': ['5', '6', '7'], 
     '3': ['8', '9', '10'],
     '4': []  # or None, doesn't matter
 }
}

但是,我正在尝试考虑多层嵌套,所以如果原始图表看起来像:

{
   '1': ['2', '3', '4'],
   '2': ['5', '6', '7'],
   '3': ['8', '9', '10'],
   '7': ['11', '12']
}

最终结构如下所示:

{
 '1': {
     '2': ['5', '6', {'7': ['11', '12']}], 
     '3': ['8', '9', '10'],
     '4': []  # or None, does not matter
 }
}

我能想到的最简单的方法是暴力破解并多次迭代图形和 "move" 周围的键,但我希望有一个更高效、更清洁的解决方案。

这不会产生您要求的 'exactly' 格式的输出,但希望它足够接近可用。

def flatten_dict(in_dict):
    in_dict_keys = in_dict.keys()
    in_dict_values = in_dict.values()
    in_dict_values_list = []
    for value1 in in_dict_values:
        for value2 in value1:
            in_dict_values_list.append(value2)
    flattenned_dict = in_dict.copy()

    "create new dict with 'substtitutions'"
    for key in in_dict_keys:
        for i, value in enumerate(in_dict[key]):
            if value in in_dict_keys:
                flattenned_dict[key][i] = {value:in_dict[value]}
    "clean up new dict"
    for value in in_dict_values_list:
        if value in flattenned_dict:
            del flattenned_dict[value]

    return flattenned_dict

if __name__ == "__main__":
    input1 = {'1': ['2', '3', '4'],'2': ['5', '6', '7'],'3': ['8', '9', '10'],}
    input2 = {'1': ['2', '3', '4'],'2': ['5', '6', '7'],'3': ['8', '9', '10'],'7': ['11', '12']}
    flattenned_dict = flatten_dict(input2)
    print(flattenned_dict)