How to order a dictionary with a key

Asked

Viewed 477 times

0

I have a dictionary as follows:

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

viraria

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?

1 answer

1


First, a reading that will possibly be interesting:

What is the difference between ordered, unordered and Sorted?

It doesn’t make much sense that you want to order a dictionary, because the implementation of it does not guarantee an order - a dictionary represents a table hash And it doesn’t even make sense that you want to order it. But if the need is to access in order the values of the dictionary, alternatively you can convert the contents of the dictionary to a list, sort it (which now makes sense, because it’s a list) and access the respective values in the dictionary by following the ordered list. 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. 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 on Ideone.

Or, if you really need to have the values stored in a dictionary, starting with version 3.1 of Python, the library collections has the implementation of the class OrderedDict, which stores the values in the order they are entered. Then, similar to the previous one, just convert the dictionary to a list, sort it and convert it into 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 on Ideone.

Note that while the condition is only the third value of the tuple, it is not guaranteed the order of the values whose third value is equal to each other.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.