How to split a nested dictionary

Question:

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?

Asked By: DISC-O

||

Answers:

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()
Answered By: Jason Baker

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()}
Answered By: Yulia V

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)
Answered By: Muntasir Aonik
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.