How to sort a dictionary that takes a tuple with key

0

I have a dictionary like this:

dicionario = {(0,0,0):['alguma informacao']}

How can I sort this dictionary from one of the key information? For example:

dicionario = {(0,0,0):['alguma informacao'],(0,0,1):['alguma informacao'],(0,0,2):['alguma informacao'],(0,0,5):['alguma informacao'],(0,1,0):['alguma informacao']}

would become

dicionario = {(0,0,0):['alguma informacao'],(0,1,0):['alguma informacao'],(0,0,1):['alguma informacao'],(0,0,2):['alguma informacao'],(0,0,5):['alguma informacao']}

if ordered from the third key item.

How can I do this?

    
asked by anonymous 29.08.2017 / 14:48

1 answer

1

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.

    
29.08.2017 / 15:31