以下是文件输出:
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':”,但实际上是输出文件中的“橙色”。
在这种情况下,我必须打印或更改密钥不存在于输出文件中。请帮帮我。如何做到这一点
使用
in
关键字。如果只想在键存在时获取该值(如果不存在则避免尝试获取该值的异常),则可以使用字典中的
get
函数,将可选默认值作为第二个参数传递(如果不传递,则返回None
):相关问题 更多 >
编程相关推荐