检查python dict中是否存在密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44035287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:39:20  来源:igfitidea点击:

Check key exist in python dict

pythonpython-2.7

提问by pioltking

Below is the file output:

下面是文件输出:

apples:20
orange:100

Below is the code:

下面是代码:

d = {}
with open('test1.txt') as f:
    for line in f:
        if ":" not in line:
                continue
        key, value = line.strip().split(":", 1)
        d[key] = value

for k, v in d.iteritems():
    if k == 'apples':
         v = v.strip()
         if v == 20:
             print "Apples are equal to 20"
         else:
             print "Apples may have greater than or less than 20"   
    if k == 'orrange':
         v = v.strip()
         if v == 20:
            print "orange are equal to 100"
         else:
            print "orange may have greater than or less than 100"

In above code i am written "if k == 'orrange':", but its actually "orange" as per output file.

在上面的代码中,我写的是“if k == 'orrange':”,但根据输出文件,它实际上是“橙色”。

In this case I have to print orrange key is not exist in output file. Please help me. How to do this

在这种情况下,我必须打印输出文件中不存在 orrange 键。请帮我。这该怎么做

回答by Pedro von Hertwig Batista

Use the inkeyword.

使用in关键字。

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the getfunction from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns Noneinstead):

如果您只想在键存在时获取值(如果不存在则避免尝试获取它的异常),那么您可以使用get字典中的函数,传递一个可选的默认值作为第二个参数(如果您不要传递它,而是返回None):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')