繁体   English   中英

检查键存在于python dict中

[英]Check key exist in python dict

以下是文件输出:

apples:20
orange:100

以下是代码:

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"

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

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

使用in关键字。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM