检查键存在于python dict中

pio*_*ing 20 python python-2.7

以下是文件输出:

apples:20
orange:100
Run Code Online (Sandbox Code Playgroud)

以下是代码:

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"
Run Code Online (Sandbox Code Playgroud)

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

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

Ped*_*sta 50

使用in关键字.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')
Run Code Online (Sandbox Code Playgroud)

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

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')
Run Code Online (Sandbox Code Playgroud)

  • 由于python懒惰地评估布尔条件,因此您可以将'if'语句简化为如下所示:`if 'apples' in d and d['apples'] == 20: ...`。解释器将检查字典中的“apples”键,只有当它存在时,解释器才会继续获取它。 (2认同)