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
Post a Comment