繁体   English   中英

Python 排序字典列表

[英]Python sort a list of dictionaries

我有一个这样的字典列表:

list = [

        {'name': 'title1', 'description': 'text1'},
        {'name': '[test] title2', 'description': 'text2'},
        {'name': 'title3', 'description': 'text3'},
        {'name': '[test] title4', 'description': 'text4'}
]

当键“名称”包含单词“[test]”时,我需要排除所有字典,然后按值“名称”排序。 我怎样才能做到这一点? 提前致谢

使用列表推导:

sorted((element for element in list if element['name'] != 'test'), key=lambda element: element.get('name'))

您可以通过几个列表操作来解决这个问题:

result = sorted(
    # filter the list on items that have name
    filter(lambda i: "name" in i and "test" not in i["name"], list),

    # sort on this name
    key=lambda i: i['name']
)

暂无
暂无

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

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