## Question:

Hi, I'm trying to sort my dictionary but I'm having difficulties.

```
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'] }
```

## Answer:

There is – but you have to understand the possible steps before you can do something like this. The `sort`

method of lists (or the `sorted`

function) accepts as an optional parameter a "sort key" function. This function takes as argument an element of the list being sorted, and must return a data type that when compared with the normal operators ( `<`

, `==`

, `>`

) results in the sorting in the desired order.

So what's needed: read these dates into a format where they're comparable in ascending order – this could be either a `date`

type object or a string of year-month-day format.

Now, even applying `.sort`

to lists on all values in the dictionary, it is not possible (or at least not practical) to fetch the corresponding date in *another* list – since the `key`

function will only receive as a parameter the elements of the list that is being ordered. The solution then is to temporarily add the (sortable) dates to the list that will be sorted, do the sorting, and extract those dates back. If each element of each list is a tuple, where the first element is the corresponding date, and the second element is the original value, we actually don't even need to use the key function: the dates being the first element of each tuple will already be compared to the desired weights.

Summing up:

- extract the dates into a sortable list
- for each list to sort:
- turn each list element into a pair (date, element)
- sort the list
- transform each element of the list back, discarding the date

- reinstate 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'] ,'Consistencia Level' : ['0','2','1'] ,'Data' : ['01/12/1996','01/12/1999','01/12/1994'] } sort_by_date_values(dict_)

We have the output:

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