简体   繁体   中英

Sort list according to values in nested dict

I have a nested dict, I want get a sorted list (AZ) of the base keys according to one of the nested values, name .

my_dict: {
    'RED':{'name':'Pen', 'number':5},
    'YEL':{'name':'Dog', 'number':1},
    'BLU':{'name':'Ball', 'number':3}
}

The correct output for the example would be:

my_list = ['BLU', 'YEL', 'RED']

At the moment, I have an ugly solution, it relies on the code always being 3 chars long.

my_list = []
for code in my_dict:
    my_list.append(my_dict[code]['name'] + code)
my_list = sorted(my_list)
my_list = [x[-3:] for x in my_list]

You can use the key argument of the sorted function:

my_dict = {
    'RED':{'name':'Pen', 'number':5},
    'YEL':{'name':'Dog', 'number':1},
    'BLU':{'name':'Ball', 'number':3}
}

my_list = sorted(my_dict, key = lambda x: my_dict[x]['name'])

print(my_list)

Output:

['BLU', 'YEL', 'RED']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM