简体   繁体   English

如何以这种方式对字典列表进行排序?

[英]How do I sort a list of dictionaries this way?

Suppose You have a list of dictionaries like the below.假设您有一个字典列表,如下所示。

data = [
    
    {
        'id':1,
        'name':'ABC corporation',
        'state': 'WA'
    },
    {
        'id':2,
        'name':'ABC corporation',
        'state': 'QLD'
    },
    {
        'id':3,
        'name':'ABC corporation',
        'state': 'WA'
    },
    {
        'id':4,
        'name':'ABC corporation',
        'state': 'QLD'
    },
    {
        'id':5,
        'name':'ABC corporation',
        'state': 'WA'
    }
]

I want all the dictionaries where state == QLD to come before others (ie which state is given has to come first. so the result will be:我希望state == QLD的所有字典都排在其他字典之前(即必须先给出哪个状态。所以结果将是:



data = [
    {
        'id':2,
        'name':'ABC corporation',
        'state': 'QLD'
    },
    {
        'id':4,
        'name':'ABC corporation',
        'state': 'QLD'
    },
    {
        'id':1,
        'name':'ABC corporation',
        'state': 'WA'
    },
    
    {
        'id':3,
        'name':'ABC corporation',
        'state': 'WA'
    },
    
    {
        'id':5,
        'name':'ABC corporation',
        'state': 'WA'
    }
]

Note: Not just normal sorting.注意:不仅仅是正常的排序。 I want to sort according to the state, only if the state value is matched.我想根据状态排序,只有状态值匹配。 My concern is that the given state dictionary data will be before other state's data.我担心的是给定的状态字典数据将在其他状态的数据之前。

Try this, it returns "" on "QLD" , which should always be the "first" string when sorting:试试这个,它在"QLD"上返回"" ,在排序时它应该始终是 "first" 字符串:

def my_sort(x):
    if x["state"] == "QLD":
        return ""
    else:
        return x["state"]

sorted_data = list(sorted(data, key=my_sort))
print(sorted_data)

Python: Sorting HOW TO Python:排序如何

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

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