简体   繁体   中英

How to sort a list of nested dictionaries with different keys

I have the following list:

mylist = [
   { 'frame': { 'aaa': 50 } },
   { 'frame': { 'bbb': 12 } },
   { 'frame': { 'ccc': 23 } },
   { 'frame': { 'ddd': 72 } }
]

I was hoping to sort the list based on those integer values with different keys 'aaa', bbb', 'ccc', etc.

I have seen this question but the keys are consistent to this problem.

Any help is highly appreciated!

EDIT: My desired output is:

sorted_list = [
       { 'frame': { 'ddd': 72 } },
       { 'frame': { 'aaa': 50 } },
       { 'frame': { 'ccc': 23 } },
       { 'frame': { 'bbb': 12 } }
]
mylist = sorted(mylist, key=lambda k: -list(k["frame"].values())[0])
print(mylist)

Prints:

[{'frame': {'ddd': 72}}, 
 {'frame': {'aaa': 50}}, 
 {'frame': {'ccc': 23}}, 
 {'frame': {'bbb': 12}}]

You can usesorted with a lambda for the key which just returns the first value stored in the dict under the 'frame' key.

We get the first value by using next with iter . This avoids creating a new list object.

We also pass the reverse parameter as True , so we get biggest numbers first. :

>>> mylist = [
...    { 'frame': { 'aaa': 50 } },
...    { 'frame': { 'bbb': 12 } },
...    { 'frame': { 'ccc': 23 } },
...    { 'frame': { 'ddd': 72 } }
... ]

>>> sorted(mylist, key=lambda d: next(iter(d['frame'].values())), reverse=True)
[{'frame': {'ddd': 72}},
 {'frame': {'aaa': 50}},
 {'frame': {'ccc': 23}},
 {'frame': {'bbb': 12}}]

A slight tweak to the answer in that question gets you this which works.

sorted_list = sorted(mylist, key=lambda k: k['frame'][list(k['frame'].keys())[0]], reverse=True)

Essentially it just goes down into the list, To then sort by the values. Set reverse to True to get it to reverse the list.

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