Home > Mobile >  Generate new keys on descending order of values in nested dictionary
Generate new keys on descending order of values in nested dictionary

Time:07-14

Input dictionary is

dict1={'AB':{'QB':0.11,'CD':0.10,'DE':0.4},'CD':{'FE':0.33,'TEW':0.22,'FEW':0.99,'FEQ':0.45}}

Output dictionary is

output={'AB':{2:{'QB':0.11},3:{'CD':0.10},1:{'DE':0.4}},
    'CD':{3:{'FE':0.33},4:{'TEW':0.22},1:{'FEW':0.99},2:{'FEQ':0.45}}}

is there a way to generate the output dictionary from the inner dictionary. In output dictionary, the keys in inner dictionary are generated on the basis of descending order of values in nested dictionary.

CodePudding user response:

Try the following:

from operator import itemgetter

dict1={'AB':{'QB':0.11,'CD':0.10,'DE':0.4},'CD':{'FE':0.33,'TEW':0.22,'FEW':0.99,'FEQ':0.45}}

def sorted_items(dct):
    return sorted(dct.items(), key=itemgetter(1), reverse=True)

def process_inner(dct):
    return {i: {k: v} for i, (k, v) in enumerate(sorted_items(dct), start=1)}

output = {k_outer: process_inner(dct_inner) for k_outer, dct_inner in dict1.items()}

print(output)
# {'AB': {1: {'DE': 0.4}, 2: {'QB': 0.11}, 3: {'CD': 0.1}}, 'CD': {1: {'FEW': 0.99}, 2: {'FEQ': 0.45}, 3: {'FE': 0.33}, 4: {'TEW': 0.22}}}

It looks a little complicated, but the idea is to use sorted to sort the items of inner dictionary according to their values (which is done by sorted_items), and then use enumerate to assign numbers to them.

  • Related