Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 (i.e. which state is given has to come first.
so the result will be:



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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this, it returns "" on "QLD", which should always be the "first" string when sorting:

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

sorted_data = list(sorted(data, key=my_sort))
print(sorted_data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading