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

时间:2016-01-16 20:46:26

标签: python list dictionary graph list-comprehension

我有一个代表如下图形的字典:

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

我想“扁平化”它,以便我最终得到类似的东西:

{
 '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
 }
}

我能想到这样做的最简单的方法就是强制它并在图表上多次迭代并“移动”键,但我希望有一个更高效,更清洁的解决方案。

1 个答案:

答案 0 :(得分:0)

这不会产生按照您的要求“完全”格式化的输出,但希望它足够接近可用。

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)