Will an error always occur when trying to access a key that doesn't exist?

Question

Will an error always be generated when trying to access a key which doesn’t exist in a dictionary?

Answer

Yes, an error will always be generated so care must be taken to check that the key exists OR exception handling must be used to handle an exception generated by the invalid key. If iterating over the keys in a dictionary provided by the keys() function, then it is safe to assume the key exists.

7 Likes

How is using an iteration better than getting an error message? I mean, both ways you will know that the ‘key’ doesn’t exist. So what makes the difference?

1 Like

Yes, but by iterating through the dictionary, you will at least not get an error.

1 Like

You don’t want your code to throw an error. I will crash your program in all likelihood.

1 Like

You could choose to handle the error instead:

my_keys = { 1: "one", 2: "two" }
try:
  print(my_keys[3])
except KeyError:
  print("3 not in my_keys!")

It’s not inherently wrong to do that - depends on the situation and your personal coding style or the coding style of your team.

2 Likes