Change nesting order of triple-nested Python dictionary -


i have dictionary three-level nesting, eg:

d = {     'sp1':{         'a1':{'c1':2,'c2':3},         'a2':{'c3':1,'c4':4}         },     'sp2':{         'a1':{'c1':3,'c2':3},         'a2':{'c3':2,'c4':0}         }     } 

all 2nd-level dictionaries contain same elements, want change to

d2 = {'a1':{'c1':{'sp1':2,'sp2':3}, 'c2':{'sp1':3,'sp2':3}}} 

i.e. switch nesting order. when write code like

d2 = {} d2['a1']['c1']['sp1'] = 2 

it throws keyerror whatever values happens 'a1'. how perform such operation?

to this, can use defaultdict, allows define default initialization action on dict.

in case, want reverse-order recursive defaultdict, classmethod reverse_recursive_make() unrolls , reverses key order:

  • when passed in key-value pair or none, returns (toplevel) dict
  • when passed in dict, recurses each of {k:v} pairs

i'm not going write code because want can more achieved sql, commented.

footnote: version lambdas (comment below) perfect.

(if insist on using dicts, , not other data structure)


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -