如何测试字典中的键是否存在?

编程入门 行业动态 更新时间:2024-10-18 16:50:27
本文介绍了如何测试字典中的键是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有人知道如何测试,例如,字典''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)"也是有效的。 请参阅: docs.python/tut/node7.htm...00000000000000 -Jeff 2007年3月10日13:17:11 -0800,Frank< su ****** @ gmailwrote:

Alternatively, "exampledict.has_key("a")" is also valid. See: docs.python/tut/node7.htm...00000000000000 -Jeff On 10 Mar 2007 13:17:11 -0800, Frank <su******@gmailwrote:

有没有人知道如何测试,例如,字典''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 - mail.python/mailman/listinfo/python-list

更多推荐

如何测试字典中的键是否存在?

本文发布于:2023-11-06 14:06:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563898.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是否存在   字典   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!