sort list of dictionaries by key that contains None key

Asked

Viewed 50 times

0

How can I sort a list of dictionaries by a certain key when within those dictionaries there is one with the key None?

Example:

mylist = [{'category': 'director'}, {'category': 'manager'}, {'category': None}]
mylist.sort() # causa erro porque não se pode comprar dict < dict

# causa erro porque não se pode comprar str < NoneType
result = sorted(mylist, key=lambda c: c['category'])

The main idea is always to get the most important from the list with the following level of relevance: director > manager and manager > None

1 answer

2


The idea is to always compare data of the same type. The easiest (and clearest) way is to map the values you have to integer values and sort the list according to these numbers.

PRIORIDADE = {
    'director': 1,
    'manager': 2
}

So to sort, instead of using the real value, use the mapped value:

result = sorted(mylist, key=lambda c: PRIORIDADE.get(c['category'], 999))

Thus, any value that does not have a defined priority, including the None, will be considered 999, being at the end of the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.