检查键存在于python dict中

时间:2017-05-17 21:47:29

标签: python python-2.7

以下是文件输出:

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键。请帮我。怎么做

1 个答案:

答案 0 :(得分:42)

使用in关键字。

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

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

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