Home > database >  Selection of Some Values in List from Nested Dictionary
Selection of Some Values in List from Nested Dictionary

Time:05-25

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?

CodePudding user response:

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']}
  • Related