Python sort list of dictionaries by key and value in separate orders

Asked

Viewed 216 times

-1

How to sort a list of dictionaries for example:

nomes = [{'nome': 'joao', 'sobrenome' 'alves'},{'nome': 'joao', 'sobrenome' 'silva'}]
  • In alphabetical order the names
  • In reverse order, surnames that is: in the normal sense the name and in the reverse sense the surname
  • You want a way out like: João Alves, João Silva ?

  • João Silva, João Alves. In this case there is only one type of name, but I wanted the tiebreaker to be in the reverse order of the surname, or the opposite of the alphabetical order

1 answer

0


In python the sort of a list is guaranteed stable, that is, in the case of equal comparisons the initial order of the elements is preserved.

Possession of this information makes the problem simple. First it is ordered reversally by the surname, then it is ordered directly by the name.

The following is an example of code implementation:

nomes = [{'nome': 'marcelo', 'sobrenome': 'alves'},
        {'nome': 'joao', 'sobrenome': 'tavares'},
        {'nome': 'joao', 'sobrenome': 'alves'},
        {'nome': 'joao', 'sobrenome': 'nogueira'},
        {'nome': 'joao', 'sobrenome': 'silva'},
        {'nome': 'barbara', 'sobrenome': 'wilson'},
        {'nome': 'antonio', 'sobrenome': 'silva'}]

nomes.sort(key = lambda i: i['sobrenome'], reverse = True)
nomes.sort(key = lambda i: i['nome'])

[print("{:10} {:10}".format(item['nome'], item['sobrenome'])) for item in nomes]

Browser other questions tagged

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