close

How do I avoid KeyError when working with dictionaries?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I avoid KeyError when working with dictionaries in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I avoid KeyError when working with dictionaries?

  1. How do I avoid KeyError when working with dictionaries?

    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.

  2. avoid KeyError when working with dictionaries

    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.

Method 1

You generally use .get with a default

get(key[, default])

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.

So when you use get the loop would look like this:

for item in newS:
    functionField = functionTable.get(item, "00")
    registerField = registerTable.get(item, "00")
    print(functionField + registerField)

which prints:

1000
0000
0000

If you want to do the explicit check if the key is in the dictionary you have to check if the key is in the dictionary (without indexing!).

For example:

if item in functionTable:   # checks if "item" is a *key* in the dict "functionTable"
    functionField = functionTable[item]  # store the *value* for the *key* "item"
else:
    functionField = "00"

But the get method makes the code shorter and faster, so I wouldn’t actually use the latter approach. It was just to point out why your code failed.

Method 2

There is no key ‘LD’ in registerTable. Can put a try except block :

try:
   a=registerTable[item]
      ...
except KeyError:
   pass

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read