Home > Back-end >  How to split a nested dictionary
How to split a nested dictionary

Time:10-09

I have the following dict:

nested_dict={4.0: {'high': 93.34, 'low': 91.53},
 7.0: {'high': 13.95, 'low': 13.88},
 9.0: {'high': 48.84, 'low': 48.36}}  # ...continues

In the interest of full disclosure I want to map this dict to the index of a data frame, creating 2 new cols: 'high', and 'low'. After multiple attempts to map the nested dict to the index failed, the easiest solution seems to be to break the dict into 2, because that can easily be mapped:

high_dict={4.0:93.34, 7.0:13.95, 9.0: 48.84} # ...continues
low_dict ={4.0:91.53, 7.0:13.88, 9.0: 48.36} # ditto

The rest is easy:

df['high']= df.index.map(high_dict)
df['low'] = df.index.map(low_dict)

How do I split the above-nested dict into my desired 2 new dicts?

CodePudding user response:

You could use Python Dictionary Comprehension to achieve it in a pandas-independent way:

high_dict={key : value['high'] for key, value in nested_dict.items()}
low_dict ={key : value['low'] for key, value in nested_dict.items()}

CodePudding user response:

You can achieve it by this way:

nested_dict={4.0: {'high': 93.34, 'low': 91.53},
 7.0: {'high': 13.95, 'low': 13.88},
 9.0: {'high': 48.84, 'low': 48.36}}

high_dict = {}
low_dict = {}

for k, v in nested_dict.items():
    high_dict[k] = v['high']

for k, v in nested_dict.items():
    low_dict[k] = v['low']
    
print(high_dict)
print(low_dict)

CodePudding user response:

df = pd.DataFrame(nested_dict).transpose().reset_index(names="key")

high = df.set_index("key")["high"].to_dict()
low = df.set_index("key")["low"].to_dict()

CodePudding user response:

As you have the tag, you can just use a transposition:

out = pd.DataFrame.from_dict(nested_dict, orient='index').to_dict()

output:

{'high': {4.0: 93.34, 7.0: 13.95, 9.0: 48.84},
 'low': {4.0: 91.53, 7.0: 13.88, 9.0: 48.36}}

If you need variables:

high_dict = out['high']
low_dict  = out['low']

For a pure python solution with a single loop over the input dictionary:

high_dict = {}
low_dict = {}
mapper = {'high': high_dict, 'low': low_dict}

for key, d in nested_dict.items():
    for k, v in d.items():
        if k in mapper:
            mapper[k][key] = v

high_dict
# {4.0: 93.34, 7.0: 13.95, 9.0: 48.84}

low_dict
# {4.0: 91.53, 7.0: 13.88, 9.0: 48.36}
  • Related