python - Flattening a dictionary representing a graph into a dictionary of lists -


i have dictionary represents graph looks so:

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

i'd "flatten" such end like:

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

however, i'm trying account multiple levels of nesting, if original graph looked like:

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

the final structure like:

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

the easiest way can think of doing brute forcing , iterating on graph several times , "move" keys around, hoping more efficient, cleaner solution.

this not produce output formatted 'exactly' asked for, close enough usable.

def flatten_dict(in_dict):     in_dict_keys = in_dict.keys()     in_dict_values = in_dict.values()     in_dict_values_list = []     value1 in in_dict_values:         value2 in value1:             in_dict_values_list.append(value2)     flattenned_dict = in_dict.copy()      "create new dict 'substtitutions'"     key in in_dict_keys:         i, value in enumerate(in_dict[key]):             if value in in_dict_keys:                 flattenned_dict[key][i] = {value:in_dict[value]}     "clean new dict"     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) 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -