Check if a key exists in a dictionary

Asked

Viewed 7,278 times

4

How can I check if a key exists inside a Python dictionary?

  • 1

    What would be a variable within a dictionary? It would be a certain dictionary key?

  • That, for example:a = {"a" : "apple"} How do I check if a is a dictionary key

1 answer

6


To check if a certain key exists in a dictionary in Python, just do:

if "chave" in dicionario:
    print("O dicionário possui a chave")

That is, if we consider the dictionary:

d = {'a': "Valor de A", 'b': "Valor de B"}

We can do:

if 'a' in d:
    print("Dicionário possui a chave 'a'")

if 'b' in d:
    print("Dicionário possui a chave 'b'")

if 'c' in d:
    print("Dicionário possui a chave 'c'")

See working on Ideone

The output generated is:

Dicionário possui a chave 'a'
Dicionário possui a chave 'b'
  • Thank you very much friend!

Browser other questions tagged

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