尝试从字典中检索键值时获取"KeyError:"



我的函数"getint"返回以下值:

响应: 0 编号: 70402 类型: 1 有价值 整数值:15

我将上述值存储在字符串 s 中,并编写了下面的代码来打印"int 值"数据 15。

法典:

s= '''response: 0
      id: 70402
      type: 1
      has value
      int value: 15
   '''
s=s.replace("has","has:")
s = s.strip()
print s
d = {}
for i in s.split('n'):
    try:
        key, val = i.split(":")
        d[key.strip()] = val.strip()
        print d['int value']
    except ValueError:
        print "no key:value pair found in", i

在输出中获取KeyError:'int value' .

输出:

  response: 0
  id: 70402
  type: 1
  has: value
  int value: 15 Traceback (most recent call last):   File "/home/tests/test_lang.py", line 18, in <module>
print d['int value'] KeyError: 'int value'

你的代码有几个问题。请尝试以下操作。

for i in s.split('n'):
    key, val = i.split(":")
    d[key.strip()] = val.strip()
try:
    print(d['int value'])
except KeyError:
    print("no 'int value' found in", d)

解释

  1. 使用KeyError捕获关键错误。
  2. 仅在您尝试捕获错误的代码部分使用 try/except
  3. 除非您有特定原因,否则您可以在创建字典后按上述方式检查密钥。

你的错误,因为当你通过s tring.您的第一i: response = 0但是你print d['int value'] d当时没有的。这将起作用:

s= '''response: 0
  id: 70402
  type: 1
  has value
  int value: 15
'''
s=s.replace("has","has:")
s = s.strip()
print s
d = {}
for i in s.split('n'):
    try:
        key, val = i.split(":")
        d[key.strip()] = val.strip()
    except ValueError:
        print "no key:value pair found in", i
print d['int value']

如果要使用密钥获取错误。您应该添加:

except KeyError:
    print "key error found in", i

或者只是将ValueError更改为KeyError

print d['int value']写在循环的外侧

s= '''response: 0
      id: 70402
      type: 1
      has value
      int value: 15
   '''
s=s.replace("has","has:")
s = s.strip()
print s
d = {}
for i in s.split('n'):
    try:
        key, val = i.split(":")
        d[key.strip()] = val.strip()
    except ValueError:
        print "no key:value pair found in", i
print d['int value']

最新更新