0

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?

1
  • Not sure what you mean Rodrigo - works fine for me Commented Oct 8, 2022 at 17:19

4 Answers 4

2

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()} 
Sign up to request clarification or add additional context in comments.

Comments

1

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) 

Comments

1

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} 

1 Comment

An interesting way to turn a nested dict into a df. For my application I dont even do the interim step in python but just map pd.DataFrame.from_dict(nested_dict, orient='index') directly via merge.
0
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() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.