Browse Python dictionary from the end

Asked

Viewed 1,149 times

1

I wonder if there is a way to go through the keys of a dictionary backwards? For example, in a dictionary d1 ={1: [], 2: [], 3: [], ..} start with key 3. I know it is possible to go through from the beginning with for, but I need to start with the last key or a specific key.

1 answer

2


There is a way, but it is necessary to understand that it is not possible to order a dictionary.

How to order a dictionary with a key

Sort dictionary by Python value

Sort dictionary by value and use rule if value is first python

What is the difference between ordered, unordered and Sorted?

However, to access the indexes in the desired order, you need to generate a list of all the indexes, sort it and browse it by accessing the respective position in the dictionary. In Python, this would look something like:

# Dicionário:
dicionario = {1: "a", 2: "b", 3: "c"}

# Gera a lista com os índices:
indices = list(dicionario.keys())

# Ordena a lista de índices em ordem reversa:
indices = reversed(indices)

# Percorre a lista de índices, acessando a respectiva posição:
for indice in indices:
    print(dicionario[indice])

The exit will be:

c
b
a

See working on Ideone.

In a simplified way, the same can be done with:

for indice in sorted(dicionario, reverse=True):
    print(dicionario[indice])

For, when iterating over a dictionary, only its index is considered. Thus, the function sorted returns the inversely ordered index list.

See working on Ideone.

  • From to use the Ordereddict module Collections

Browser other questions tagged

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