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.
>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)