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']}
First thing: Call the variable
dict
is a bad choice.dict
is used internally bypython
with atype
.– Wallace Maxters