I'm writing a Django project as a student intern. I have the following dictionary of list of data in my python file :
list_sequences = {'01': [["Calcul Red Shift", "2014-09-24", "Running"]],
'02': [["Calcul Dérive", "2014-09-22", "Stopped"]],
'03': [["Calcul simple", "2014-04-12", "Paused"]],
'04': [["Calcul Mental", "2014-02-14", "Failed"]],
'05': [["Sauvegarde des données", "2014-12-22", "Running"]],
'06': [["Envoi des données", "2014-07-17", "Stopped"]],
'07': [["Calcul de LA question", "2015-01-06", "Running"]],
'08': [["Refactorisation", "2014-09-24", "Paused"]],
'09': [["Cuisson de choucroute", "2013-11-13", "Running"]],
'10': [["Ecriture du rapport", "2014-02-03", "Running"]],
'11': [["Nettoyage des fichiers", "2014-09-24", "Paused"]],
'12': [["Création des utilisateurs", "2015-01-06", "Failed"]]
}
As you can see, the key of each element is 01, 02, ...
I also use double [[ ]] because I use strings and otherwise the webpage shows only one character in the table cells.
What I would like to do is sorting the whole dictionary by date.
I tried the following :
list_sequences = collections.OrderedDict(sorted(list_sequences.items(), key=lambda e: e[0][1]))
and also this :
list_sequences = collections.OrderedDict(sorted(list_sequences.items(), key=lambda e: datetime.datetime.strptime(e[0][1], '%Y-%m-%d')))
But it doesn't seem to work. The first one sorts my list in a weird way and the second one throws me a :
time data '0' does not match format '%Y-%m-%d'
Any idea ?
Thanks a lot !
dict.items()
returns (key, value) pairs, so the value is at index 1( e[1]
) not 0( e[0]
). You need to change e[0][1]
to e[1][0][1]
.
Demo:
>>> OrderedDict(sorted(list_sequences.items(), key=lambda e:datetime.strptime(e[1][0][1], '%Y-%m-%d')))
OrderedDict([('09', [['Cuisson de choucroute', '2013-11-13', 'Running']]), ('10', [['Ecriture du rapport', '2014-02-03', 'Running']]), ('04', [['Calcul Mental', '2014-02-14', 'Failed']]), ('03', [['Calcul simple', '2014-04-12', 'Paused']]), ('06', [['Envoi des donn\xc3\xa9es', '2014-07-17', 'Stopped']]), ('02', [['Calcul D\xc3\xa9rive', '2014-09-22', 'Stopped']]), ('11', [['Nettoyage des fichiers', '2014-09-24', 'Paused']]), ('01', [['Calcul Red Shift', '2014-09-24', 'Running']]), ('08', [['Refactorisation', '2014-09-24', 'Paused']]), ('05', [['Sauvegarde des donn\xc3\xa9es', '2014-12-22', 'Running']]), ('12', [['Cr\xc3\xa9ation des utilisateurs', '2015-01-06', 'Failed']]), ('07', [['Calcul de LA question', '2015-01-06', 'Running']])])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.