简体   繁体   English

python中嵌套字典的排序列表

[英]sorting list of nested dictionaries in python

I have something like 我有类似的东西

[
    {
        "key": { "subkey1":1, "subkey2":"a"  }
    },
    {
        "key": { "subkey1":10, "subkey2":"b" }
    },
    {
        "key": { "subkey1":5, "subkey2":"c" }
    }
]

And would need to have : 并且需要具有:

[
    {
        "key": { "subkey1":10, "subkey2":"b" }
    },
    {
        "key": { "subkey1":5, "subkey2":"c" }
    },
    {
        "key": { "subkey1":1, "subkey2":"a" }
    }
]

Many thanks! 非常感谢!

EDIT : I'd like to sort by subkey1, this wasn't clear previously. 编辑:我想按subkey1进行排序,这之前还不清楚。

Use the key keyword to the sorted() function and sort() method : key关键字用于sorted()函数sort()方法

yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)

Demo: 演示:

>>> yourdata = [{'key': {'subkey': 1}}, {'key': {'subkey': 10}}, {'key': {'subkey': 5}}]
>>> yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)
>>> yourdata
[{'key': {'subkey': 10}}, {'key': {'subkey': 5}}, {'key': {'subkey': 1}}]

This assumes that all top-level dictionaries have a key key, which is assumed to be a dictionary with a subkey key. 这假定所有顶级词典都具有key键,该key键被假定为带有subkey键键的字典。

See the Python Sorting HOWTO for more details and tricks. 有关更多详细信息和技巧,请参见Python Sorting HOWTO

假设您要按列表中每个字典d的值d['key']['subkey']排序,请使用以下命令:

sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)
sorted(yourdata, reverse=True)

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

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