First, a reading that may be interesting:
What is the difference between ordered, unordered and sorted?
It does not make much sense to order a dictionary because the implementation itself does not guarantee an order - a dictionary represents a hash table and it does not make much sense to order it. But if the need is to access the dictionary values in order, alternatively you can convert the dictionary indexes to a list, sort it (which now makes sense as it is a list) and access its values in the dictionary following the list orderly Something like:
dicionario = {
(0,0,0): ['0, 0, 0'],
(0,0,1): ['0, 0, 1'],
(0,0,2): ['0, 0, 2'],
(0,0,5): ['0, 0, 5'],
(0,1,0): ['0, 1, 0']
}
indices = sorted(dicionario.keys(), key = lambda item: item[2])
This will generate in indices
a list of tuples ordered based on the third value. In this way, just go through the ordered list, accessing the respective values in the dictionary:
for i in indices:
print(i, dicionario[i])
See working at Ideone .
Or, if you really need to have the values stored in a dictionary, starting with version 3.1 of Python, the collections
library has the implementation of the OrderedDict
class, which stores the values in the order they are entered. Then, similarly to the previous one, just convert the dictionary to a list, sort it and convert it to a OrderedDict
. Something like:
novo_dicionario = OrderedDict(sorted(dicionario.items(), key = lambda item: item[0][2]))
So, to go through this new dictionary, just do:
for key, value in novo_dicionario.items():
print(key, value)
See working at Ideone .
Note that while the condition is only the third value of the tuple, the order of values whose third value is equal to each other is not guaranteed.