检查密钥是否在字典中?

时间:2014-06-26 15:44:53

标签: python python-2.7 dictionary

如何检查字典中是否有密钥?

这是我的字典:

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

我试过这样做:

if edges[(1, 'a')]

但是我收到了一个错误:

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

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:5)

只需使用in运算符(伴随not in运算符):

if (1, 'a') in edges:

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

以下摘自Python d字典类型,其中key in d是字典:

  

True

     

如果d有一个密钥key,则返回False,否则key not in d

     

not key in d

     

相当于{{1}}。

相关问题