1

I'm new to python but have experience in perl. So I have a dictionary like this

d = { '123' : 'F'
      '124' : 'S'
      '125' : 'F'
    }

and I'm running a loop for a list which has the key values, but some may not exist in my dictionary. When I run the code I get an error

print(d[str(row[0])])


KeyError: '126'

Perl would never do this to me. Please help an ignorant programmer.

IMPERATOR
  • 277
  • 1
  • 3
  • 14

3 Answers3

2

You can use dict.get() that will never raise a KeyError exception:

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

print(d.get(str(row[0])))

Or, you can check if a key is in the dictionary before trying to get the value by the key:

key = str(row[0])
if key in d:
    print(d[key])

Or, you can also catch a KeyError exception:

key = str(row[0])
try:
    print(d[key])
except KeyError:
    print("Key '{}' not found".format(key)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • But if you're going to go to the trouble to check, it's often more better to just catch the exception. And it's considered good python style: "It's easier to ask forgiveness than to get permission", says the dictum. – alexis Mar 12 '14 at 02:36
  • @alexis agreed, thank you, will include in the answer. – alecxe Mar 12 '14 at 02:39
  • 1
    @alexis should have said "forgive me for it" :) – alecxe Mar 12 '14 at 02:43
1

I think the prefererd way is

my_dict.get(key,None)
Jeff B
  • 8,572
  • 17
  • 61
  • 140
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Python is a little more object-oriented than Perl — so you can to easily derive your own dict sublcass that does whatever you want when an attempt is made to access a missing key. However it takes more effort to write hard-to-read code, but it can be done. For example:

class MyDict(dict): __missing__ = lambda _, k: '%s?' % k

d = MyDict((('123', 'F'), ('124', 'S'), ('125', 'F'),))

row = 126, 123, 124
print(d[str(row[0])])  # -> 126?
martineau
  • 119,623
  • 25
  • 170
  • 301