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

Selection of Some Values in List from Nested Dictionary

I have an input dictionary:

dict1 = {'ABC':{'ARC':0,'MRC':1,'GEW':0,'TEQ':0},'FEW':{'VEW':1,'BDE':1,'LRQ':1}}

Expected output:

new_dict={'ABC':['MRC'],'FEW':['VEW','BDE','LRQ']}

Is there any way to select the keys of inner dictionaries in the form of a list whose values are 1 in the inner 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 :

You can traverse the items of the dictionary and add the inner keys if the inner value is 1.

dict1 = {'ABC': {'ARC': 0, 'MRC': 1, 'GEW': 0, 'TEQ': 0},
         'FEW': {'VEW': 1, 'BDE': 1, 'LRQ': 1}}
new_dict = {key: [k for k, v in dict1[key].items() if v == 1] for key in dict1}
print(new_dict)

Output:

{'ABC': ['MRC'], 'FEW': ['VEW', 'BDE', 'LRQ']}
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