Home > Net >  Nested Dictionary Manipulation
Nested Dictionary Manipulation

Time:04-30

I have a nested dictionary in this structure:

dictionary = {chapter: {section: {sub_section: {'a':{...}, 'b':{...}, 'c':{...}, 'd':{...}, 'e':{...}}}}}

Assume chapter, section, sub_section are values of list variables.

For every possible combination, key values 'a,b,c,d,e' are same.

I want 'c' dictionary to contain 'c','d','e' dictionaries.

How to convert the dictionary to the new dictionary?

new_dict = {chapter: {section: {sub_section: {'a':{...}, 'b':{...}, 'c':{ 'c':{...}, 'd':{...}, 'e'={...}}}}}}

If possible less label or name based, more index or level based approach is appreciated.

CodePudding user response:

Make a copy of the whole nested dictionary. Then copy the c, d, e elements into the new dictionary's c element, and delete the unnecessary d and e elements.

from copy import deepcopy

new_dict = deepcopy(dictionary)
ss = new_dict['chapter']['section']['subsection']
ss['c'] = {key: ss[key] for key in ['c', 'd', 'e']}
for key in ['d', 'e']:
    del ss[key]

You say you don't want this to be label based, but I don't see any logic that can be used to select the elements to be moved without just listing the labels.

  • Related