Mic*_*ael 4 python dictionary python-2.7
如何检查字典中是否有密钥?
这是我的字典:
edges = {(1, 'a') : 2,
(2, 'a') : 2,
(2, '1') : 3,
(3, '1') : 3}
Run Code Online (Sandbox Code Playgroud)
我试过这样做:
if edges[(1, 'a')]
Run Code Online (Sandbox Code Playgroud)
但是我收到一个错误:
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
Run Code Online (Sandbox Code Playgroud)
做正确的方法是什么?
只需使用in操作员(由not in操作员陪同):
if (1, 'a') in edges:
if (1, 'a') not in edges:
Run Code Online (Sandbox Code Playgroud)
以下是Python字典类型文档的摘录,其中d是字典:
key in d
True如果d有钥匙则返回key,否则False.
key not in d相当于
not key in d.