Python: How to get a dictionary key based on the value?

Asked

Viewed 147 times

-3

I have a dictionary in table format={"t":148} I can return 148 by doing table["t"], right? How can I make to return "t" based on the 148? When I try to print table[148] ends up returning "None", why?

1 answer

4

The structure of dictionaries was created in order to quickly recover a value from a key

So, see the example below:

>>> tabela = {"t":148}

>>> tabela["t"]
148

>>> tabela[148]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 148

The exception KeyError means that the key search does not exist. In order that this error does not happen and you have more control in your program, you can use a try/except or the method get() returning a value default. See below

Try/except

try:
    valor = tabela[148]
except KeyError:
    print("Esta chave não existe")

get

valor = tabela.get(148, "Esta chave não existe")
print(valor)

The result for both cases will be Esta chave não existe

Answering your question

To find the key using the value (whereas the values are unique:

for chave, valor in tabela.items():
    if valor == 148:
       break
print(chave)

The result will be t

Imagining that the structure was something like:

tabela = {"t": 148,
          "u": 200,
          "v": 148
         }

Note that the keys "t" and "v" have value 148.

So to recover multiple keys from one value, it could be something like:

resultado = []
for chave, valor in tabela.items():
    if valor == 148:
        resultado.append(chave)

print(resultado)

The result would be: ['t', 'v']

IN TIME

Retrieve key from a value SHOULD NOT be frequent in your program. If so, the structure adopted is wrong.

I hope I’ve helped.

Browser other questions tagged

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