Go through the Python dictionary from the end

0

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 that it is possible to go from the beginning with for , but I must start with the last key or a specific key.

    
asked by anonymous 21.09.2017 / 03:43

1 answer

2

It's like, but you have to understand that it's not possible to sort a dictionary.

How to sort a dictionary that takes a tuple with a key

Sort dictionary by Python value

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

What's 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 scroll through it by accessing its index 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 output will be:

c
b
a
  

See working at Ideone .

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

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

Well, when iterating over a dictionary, only its index is considered. Thus, the sorted function returns the list of indexes sorted in reverse.

  

See working at Ideone .

    
21.09.2017 / 03:54