Bonjour à tous,
J'ai une structure un peu complexe que j'aimerai trier pour obtenir un dictionnaire (le bouquin pas le type python )
Voici un exemple :
Code python : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 from collections import OrderedDict allObjs = OrderedDict() firstLetter = "R" color = "Rouge" obj = "ballon rouge" allObjs[firstLetter] = OrderedDict() allObjs[firstLetter][color] = [obj] allObjs[firstLetter][color].append("fleur rouge") allObjs[firstLetter][color].append("chapeau rouge") firstLetter = "J" color = "Jaune" obj = "veste jaune" allObjs[firstLetter] = OrderedDict() allObjs[firstLetter][color] = [obj] allObjs[firstLetter][color].append("crayon jaune") allObjs = OrderedDict(sorted(allObjs.items())) print(allObjs)
J'aimerai en plus, trier les objets par ordre alphabétique de nom
Je ne connais pas la liste des couleurs donc je ne peux pas faire :
Code python : Sélectionner tout - Visualiser dans une fenêtre à part
1
2 allObjs["J"]["Jaune"].sort() allObjs["R"]["Rouge"].sort()
ou alors cela m'oblige à reparcourir tous mon dictionnaire
Code python : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4 for firstLetter, definitions in allObjs.iteritems(): for color in definitions: allObjs[firstLetter][color].sort()
Il doit bien y avoir plus efficace
Merci pour votre aide
Partager