Python sorting of dictionary list by key and value in distinct orders

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, the surnames this is: in the normal sense the name and in the reverse sense the surname
Author: alandplm, 2019-05-31

1 answers

In python the ordering 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 the problem becomes simple. First it is ordered reversely by surname, then it is ordered directly by 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]
 0
Author: alandplm, 2019-05-31 06:00:03