简体   繁体   English

如何对具有不同键的嵌套字典列表进行排序

[英]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.我希望根据具有不同键'aaa'、bbb'、'ccc'等的 integer 值对列表进行排序。

I have seen this question but the keys are consistent to this problem.我见过这个问题,但关键是与这个问题一致。

Any help is highly appreciated!非常感谢任何帮助!

EDIT: My desired output is:编辑:我想要的 output 是:

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.您可以使用lambdasortedkey ,它只返回存储在'frame'键下的dict中的第一个值。

We get the first value by using next with iter .我们通过使用nextiter获得第一个值。 This avoids creating a new list object.这避免了创建新list object。

We also pass the reverse parameter as True , so we get biggest numbers first.我们还将reverse参数作为True传递,因此我们首先获得最大的数字。 :

>>> 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.reverse设置为 True 以使其反转列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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