Sort lists in python dictionaries

Asked

Viewed 856 times

3

Hello, I’m trying to sort my dictionary, but I’m finding it difficult.

dict = {'EstacaoCodigo' : ['1','2','3'] ,'NivelConsistencia' : ['0','2','1'] ,'Data' : ['01/12/1996','01/12/1999','01/12/1994'] }

Would it be possible to sort the list values from the date list? The expected result is:

{'EstacaoCodigo' : ['2','1','3'] ,'NivelConsistencia' : ['2','0','1'] ,'Data' : ['01/12/1999','01/12/1996','01/12/1994'] }
  • 1

    First thing: Call the variable dict is a bad choice. dict is used internally by python with a type.

2 answers

2

It has - but it has to understand the possible steps before it can do something like this. The method sort of the lists (or the function sorted) accept as an optional parameter a "sort key" function. This function takes as argument an element of the list that is being ordered, and must return a type of data that when compared to normal operators (<, ==, >) result in ordering in the desired order.

So, what is needed: read these dates to a format in which they are comparable in ascending order - this could be either an object of the type date or a string in year-month-day format.

Now, even applying the .sort in the lists at all values in the dictionary, it is not possible (or at least not practical) to search for the corresponding date in another list - since the function key will only receive as parameter the elements of the list that is being ordered. The solution then is to temporarily aggregate the (orderly) dates to the list that will be ordered, make the sorting, and extract back those dates. If each element of each list is a tuple, where the first elemnet is the corresponding date, and the second element the original value, in fact, we don’t even need to use the key function: the dates being the first element of each tuple will already be compared with the desired weights.

In short:

  • extract the dates in a checklist
  • for each list to order:
    • transform each element in the list into a pair (date, element)
    • sort the list
    • transform each element of the list back, discarding the date
  • reintegrate the key with the dates in the dictionary

Transposing these 6 steps to Python we have:

from datetime import datetime

def ordena_por_valores_de_data(dct, chave_datas='Data'):
    datas = dct.pop(chave_datas)
    datas_ordenaveis = [datetime.strptime(data, '%d/%M/%Y') for data in datas]
    for chave, lista in dct.items():
        dct[chave] = [par for par in zip(datas_ordenaveis, lista)]
        dct[chave].sort(reverse=True)
        dct[chave] = [par[1] for par in dct[chave]]
    dct[chave_datas] = datas

And when testing in interactive mode with: dict_ = {'Estacaocodigo' ['1','2','3'] ,'Nivelconsistencia' ['0','2','1'] ,'Data' ['01/12/1996','01/12/1999','01/12/1994'] } sort_)

We have the exit:

{'EstacaoCodigo': ['2', '1', '3'],
 'NivelConsistencia': ['2', '0', '1'],
 'Data': ['01/12/1996', '01/12/1999', '01/12/1994']}

0

If you only have a dictionary and want to sort a list within that dictionary, it can be used Sorted, as in the example below:

>>> d = {'EstacaoCodigo' : ['1','2','3'] ,'NivelConsistencia' : ['0','2','1'] ,'Data' : ['01/12/1996','01/12/1999','01/12/1994'] }
>>> d['Data'] = sorted(d['Data'], reverse=True)
>>> d
{'EstacaoCodigo' : ['2','1','3'] ,'NivelConsistencia' : ['2','0','1'] ,'Data' : ['01/12/1999','01/12/1996','01/12/1994'] }

If you use other ways and expose the date, it is possible that some things have to be changed in the Sorted function, but probably the Sorted will still be enough, having at most add a value key.

  • It worked, but because the date is a string ( I think) it is ordering first by day after month and then year. Now I turned it into date, but it is only ordering the list of dates the others continue in the same form datetime.strptime('01/12/1999', '%d/%m/%Y')

  • @Paulopraça did not understand the last part. Do you want to sort Estacaocodigo and Nivelconsistencia too? If yes, just apply the same process d['EstacaoCodigo'] = sorted(d['EstacaoCodigo'] ).

  • I’ll try to explain it better.

  • d['Estacaocodigo'][0] = '1' d['Data'][0] = '01/12/1999' when ordering by date, I wanted the position of the other lists to be sorted together with the dates. So: d['Estacaocodigo'][1] = '1' d['Data'][1] = '01/12/1999' I don’t know if I’m making myself clear. Maybe I have to create another dictionary by making all the values of the keys that have the same index in the same list

  • I want to sort all list values according to date

Browser other questions tagged

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