5

How to check if there a key in the dictionary?

Here is my dictionary:

edges = {(1, 'a') : 2,
         (2, 'a') : 2,
         (2, '1') : 3,
         (3, '1') : 3}

I have tried to do this:

if edges[(1, 'a')]

But I get an error:

Traceback (most recent call last):
  File "vm_main.py", line 33, in <module>
    import main
  File "/tmp/vmuser_lvzelvvmfq/main.py", line 30, in <module>
    print fsmsim("aaa111",1,edges,accepting)
  File "/tmp/vmuser_lvzelvvmfq/main.py", line 16, in fsmsim
    if edges[(1, 'a')]:
TypeError: 'dict' object is not callable

What is the right way to do it?

Michael
  • 15,386
  • 36
  • 94
  • 143

1 Answers1

9

Just use the in operator (which is accompanied by the not in operator):

if (1, 'a') in edges:

if (1, 'a') not in edges:

Below is an excerpt from the documentation of Python's dictionary type, where d is a dictionary:

key in d

Return True if d has a key key, else False.

key not in d

Equivalent to not key in d.