如何判断Python字典中是否存在非标量键

时间:2012-12-31 20:28:51

标签: python

我尝试使用'in'和has_key(),但如果键不是单个值,则这些似乎不起作用:

 >>> aarr["x","y","z"]=1
 >>> aarr["x","y","z"]
 1
 >>> if "x","y","z" in aarr:
   File "<stdin>", line 1
     if "x","y","z" in aarr:
           ^
 SyntaxError: invalid syntax
 >>> aarr.has_key("x","y","z")
 Traceback (most recent call last):
  File "<stdin>', line 1, in <module>
 TypeError: has_key() takes exactly one argument (3 given)

在两种情况下抱怨aarr.has_key(["x","y","z"])时,尝试["x","y","z"] in aarr:unhashable type: 'list'也无效。

1 个答案:

答案 0 :(得分:6)

在表达式中使用逗号时,您正在创建元组

使用元组进行测试:

if ("x","y","z") in aarr:

你也可以查看.keys()来了解这一点:

>>> aarr = {}
>>> aarr["x","y","z"]=1
>>> if ("x","y","z") in aarr:
...     print 'success!'
... 
success!
>>> aarr.keys()
[('x', 'y', 'z')]
>>> aarr.keys()[0]
('x', 'y', 'z')