Sum
Sum

Reputation: 363

Getting "KeyError:" when trying to retrieve the key value from a dictionary

My function "getint" returns below values:

response: 0 id: 70402 type: 1 has value int value: 15

I have stored the above value in String s and written below code to print the 'int value' data 15.

Code:

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

In Output getting KeyError:'int value'.

Output :

  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'

Upvotes: 0

Views: 758

Answers (3)

Artier
Artier

Reputation: 1673

Write print d['int value'] out side for loop

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']

Upvotes: 1

gaback
gaback

Reputation: 638

Your error because when you go through the s tring. Your first i: response = 0 but you print d['int value'] which d doesn't has at that time. This will work:

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']

If you want to get the error with the key. You should add:

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

Or just change ValueError to KeyError

Upvotes: 1

jpp
jpp

Reputation: 164623

There are a few problems with your code. Try the below.

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)

Explanation

  1. Use KeyError to catch key errors.
  2. Only use try / except on the part of the code where you are trying to catch an error.
  3. Unless you have a specific reason, you can as above check for the key after the dictionary is created.

Upvotes: 1

Related Questions