python di中存在Check key

2024-04-24 22:06:27 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是文件输出:

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"

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

在这种情况下,我必须打印或更改密钥不存在于输出文件中。请帮帮我。如何做到这一点


Tags: 文件key代码inforifvalueline
1条回答
网友
1楼 · 发布于 2024-04-24 22:06:27

使用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.')

相关问题 更多 >