Itemgetter - Sort list of dictionaries - Python

Asked

Viewed 1,465 times

1

Suppose I have the following list of dictionaries:

lista = [{"nome": "Maria", "idade": 15},
          {"nome": "João", "idade": 26}]

And I’m using the following function to sort:

ordenar =  sorted(lista, key=itemgetter("idade"))

But I just want you to present me the names in the descending order of age, from the highest to the lowest, ie: ["João", "Maria"] without presenting me with the entire dictionary.

3 answers

1


You can use the parameter reverse of sorted to do the Sort and create a new list with the result, leaving +/- as shown in the example below:

lista = [{"nome": "Maria", "idade": 15},
    {"nome": "João", "idade": 26}]

# Faz o sort
ordenar =  sorted(lista, key=lambda row:row['idade'] , reverse=1 )

# Criar uma array só com o nome
ordenar = [ row['nome'] for row in ordenar ]

print(ordenar)

Online example


To do the Sort for more than one column in the parameter key you will need to return a tuple as display in the example below.

sorted(lista, key=lambda row:( row['idade'], row['nome'] ) , reverse=1 )
#                            ^                           
#                          tuple com o valor de idade e nome
  • 1

    Thank you! it worked fine, just one more question, in case I wanted to order by one but show both columns, how would it look?

  • I added another example showing how Sort can be done with more than one column.

0

One solution is to take the relevant information out of dictionaries and then sort.

#formo uma nova lista só com as informações que interessam e sem o dicionário
lista_sem_dicionario =  [(dic['idade'],dic['nome']) for dic in lista]
#ordeno do maior para o menor e pego só o nome
[l[1] for l in sorted(lista_sem_dicionario, reverse=True)]

0

It got a little bigger than I imagined, but I think that way you gain more autonomy to sort and get various results.

lista = [
{"nome": "Maria", "idade": 15},
 {"nome": "João", "idade": 26}]

def organiza(lista, ordenador, *retorno):
    aux = []


    for dct in lista:
        l = []
        for i in retorno:
            l.append(dct[i])
        plv = "{} : {}".format(dct[ordenador],','.join(l))
        aux.append(plv)
    aux.sort(reverse=True)
    resultado = []
    for i in aux:
        resultado.append(i.split(':')[1].strip().split(','))
    return resultado

print(organiza(lista,'idade','nome'))

In the function above. Vc enters the list in the first argument the item by which you want to order and finally the items you want to return.

This way you can put more items in the dictionary without having to touch the function again.

Browser other questions tagged

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