如何测试字典中的键是否存在? [英] How to test if a key in a dictionary exists?

查看:57
本文介绍了如何测试字典中的键是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




有没有人知道如何测试,例如,字典''name''是否有一个名为''name_key的

键''?


这是可能的:


keys_of_names = names.keys()

L = len (keys_of_names)


for i in range(L):

if keys_of_names [i] == name_key:

print' '找到''

但肯定没有效率。我希望有类似的东西:


name.is_key(name_key)


感谢您的帮助!

Frank

Hi,

does anyone know how one can test if, e.g., a dictionary ''name'' has a
key called ''name_key''?

This would be possible:

keys_of_names = names.keys()
L = len(keys_of_names)

for i in range(L):
if keys_of_names[i] == name_key:
print ''found''
But certainly not efficient. I would expect there is something like:

name.is_key(name_key)

I appreciate your help!

Frank

推荐答案

Frank写道:
Frank wrote:




有没有人知道如何测试一个字典''name''是否有一个名为''name_key'的

键?
Hi,

does anyone know how one can test if, e.g., a dictionary ''name'' has a
key called ''name_key''?



name_key名称


例如

name_key in name

e.g.


>> name = {" john":42}
" john"名称
>>name={"john": 42}
"john" in name



True

True


>>" julie"名字
>>"julie" in name



False


- Irmen

False

--Irmen


是的,你有name.has_key(name_key),或许更好,在

运算符中:


如果name_key在名称中:

做点什么
Yes, you have name.has_key(name_key) and perhaps better, the in
operator:

if name_key in name:
do something


当然,你可以使用if key in dict测试会员资格:

Python 2.3.5(#1,2006年1月13日,20:13:11)

[GCC 4.0.1(Apple Computer,Inc。)在达尔文建立5250)]

键入帮助,版权,信用等。或许可证或欲获得更多信息。
Sure, you can use "if key in dict" to test for membership:
Python 2.3.5 (#1, Jan 13 2006, 20:13:11)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>> exampledict = {" a" :1,b :2}
a在exampledict
>>exampledict = {"a" : 1, "b" : 2}
"a" in exampledict



True

True


>>" q"在exampledict
>>"q" in exampledict



False

False


>>>
>>>



或者,exampledict.has_key(" a)"也是有效的。


请参阅:

http://docs.python.org/tut/node7.htm...00000000000000


-Jeff

2007年3月10日13:17:11 -0800,Frank< su ****** @ gmail.comwrote:

Alternatively, "exampledict.has_key("a")" is also valid.

See:

http://docs.python.org/tut/node7.htm...00000000000000

-Jeff

On 10 Mar 2007 13:17:11 -0800, Frank <su******@gmail.comwrote:





有没有人知道如何测试,例如,字典''name''有一个名为''name_key'的

键'?


这是可能的:


keys_of_names = names.keys()

L = len( keys_of_names)


for i in range(L):

if keys_of_names [i] == name_key:

print''发现''


但肯定没有效率。我希望有类似的东西:


name.is_key(name_key)


感谢您的帮助!

Frank


-
http://mail.python.org/mailman/listinfo/python-list


这篇关于如何测试字典中的键是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆