2011-08-19 83 views
9

是否有检查字典中的键的简写方式?Python中多个'in'运算符?

东西,我可以使用,而不是使用多个inand运营商 - 而不是以下:

('somekey' in d) and ('someotherkey' in d) and ('somekeyggg' in d) 
+0

这有什么错呢?它看起来非常清晰和优雅。 –

+0

如果您必须为8或9个密钥执行操作,它会变得很烦人。 –

+0

然后考虑以此为例。三个关键版本并不差,并没有显示任何实际问题。 –

回答

24
all(word in d for word in [ 'somekey', 'someotherkey', 'somekeyggg' ]) 
+1

+1该列表可以事先创建,甚至可以重复使用。 –

+3

@Gareth:你为什么添加分割? – recursive

+1

@reno对不起,选择尼特,但我相信这将是一个[生成器](http://www.python.org/dev/peps/pep-0289/)[表达式](http://docs.python。组织/参考/ expressions.html#发生器表达式)。 – Marty

5
set(['somekey', 'someotherkey', 'somekeyggg']).issubset(d)