Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate new keys on descending order of values in nested dictionary

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading