What are Python KeyError Exceptions ? Expert’s Top Picks
What-are-Python-KeyError-Exceptions-ACTE

What are Python KeyError Exceptions ? Expert’s Top Picks

Last updated on 07th Dec 2021, Blog, General

About author

Jahir Usain (RPA with Python )

Jahir Usain is a Python developer with 4+ years of experience in Python, NLP, NLTK, and IBM Watson Assistant. His articles help the learners get insights into the domain.

(5.0) | 19389 Ratings 1071

    Introduction:-

    Python’s KeyError special case is a typical exemption experienced by fledglings. Knowing why a KeyError can be raised and a few answers for keep it from halting your program are fundamental stages to improving as a Python software engineer.


Subscribe For Free Demo

[custom_views_post_title]

    What a Python KeyError Usually Means?

    A Python KeyError special case is the thing that is raised when you attempt to get to a key that isn’t in a word reference (dict).


    Python KeyError
    Python KeyError

    Python’s true documentation says that the KeyError is raised when a planning key is gotten to and isn’t found in the planning. A planning is an information structure that maps one bunch of qualities to another. The most widely recognized planning in Python is the word reference.


    The Python KeyError is a sort of LookupError special case and indicates that there was an issue recovering the key you were searching for. At the point when you see a KeyError, the semantic significance is that the key being searched for couldn’t be found.


    In the model beneath, you can see a word reference (ages) characterized with the ages of three individuals. At the point when you attempt to get to a key that isn’t in the word reference, a KeyError is raised:


      • >>> ages = {‘Jim’: 30, ‘Pam’: 28, ‘Kevin’: 33}
      • >>> ages[‘Michael’]
      • Traceback (most recent call last):
      • File “stdin”, line 1, in module
      • KeyError: ‘Michael’

    Here, endeavoring to get to the key ‘Michael’ in the ages word reference brings about a KeyError being raised. At the lower part of the traceback, you get the important data:


  • The way that a KeyError was raised
  • The key that couldn’t be found, which was ‘Michael’
  • The second-to-last line lets you know which line raised the special case. This data is more useful when you execute Python code from a document.

  • Course Curriculum

    Learn Advanced IronPython Certification Training Course to Build Your Skills

    Weekday / Weekend BatchesSee Batch Details

    In the program below, you can see the ages word reference characterized once more. This time, you will be provoked to give the name of the individual to recover the age for:

      • # ages.py
      • ages = {‘Jim’: 30, ‘Pam’: 28, ‘Kevin’: 33}
      • person = input(‘Get age for: ‘)
      • print(f'{person} is {ages[person]} years old.’)

    This code will take the name that you give at the brief and endeavor to recover the age for that individual. Whatever you type in at the brief will be utilized as the way in to the ages word reference, on line 4.


    Rehashing the bombed model from a higher place, we get another traceback, this time with data about the line in the record that the KeyError is raised from:


      • $ python ages.py
      • Get age for: Michael
      • Traceback (most recent call last):
      • File “ages.py”, line 4, in module
      • print(f'{person} is {ages[person]} years old.’)
      • KeyError: ‘Michael’

    The program bombs when you give a key that isn’t in the word reference. Here, the traceback’s last couple of lines highlight the issue. Record “ages.py”, line 4, in module lets you know which line of which document raised the subsequent KeyError special case. Then, at that point, you are shown that line. At last, the KeyError special case gives the missing key.


    So you can see that the KeyError traceback’s last line doesn’t give you enough data all alone, yet the lines before it can draw you a great deal nearer to getting what turned out badly.


    What other place will you track down a Python KeyError?

    Albeit more often than not, a KeyError is raised in view of an invalid key in a Python word reference or a word reference subclass, you may likewise think that it is in different spots in the Python Standard Library, for example, in a zipfile. Notwithstanding, it indicates a similar semantic importance of the Python KeyError, which isn’t viewing as the mentioned key.


    An illustration of such:

      • >>> from zipfile import ZipFile
      • >>> my_zip_file = ZipFile(‘Avengers.zip’)
      • >>> my_zip_file.getinfo(‘Batman’)
      • Traceback (most recent call last):
      • File “pyshell#1”, line 1, in
      • File “myzip.py”, line 1119, in getinfo
      • ‘There is no item named %r in the archive’ % name)
      • KeyError: “There is no item named ‘Batman’ in the archive”pyshell#1

    In this model, the zipfile.ZipFile class is utilized to determine data about a ZIP chronicle ‘Batman’ utilizing the getinfo() work.


    Here, the traceback demonstrates that the issue isn’t in your code yet in the zipfile code, by showing the line which caused the issue. The special case raised here isn’t a result of a LookUpError yet rather because of the zipfile.ZipFile.getinfo()function call.


    When do you have to raise a Python KeyError?

    In Python Programming, it very well may be reasonable on occasion to powerfully bring exemptions up in your own code. You can typically raise an exemption utilizing the raise catchphrase and by calling the KeyError special case:


      • >>> raise KeyError(‘Batman’)

    Here, ‘Batman’ goes about as the missing key. Nonetheless, as a rule, you ought to give more data about the missing key with the goal that your next designer has an unmistakable comprehension of the issue.


    Conditions to bring a Python KeyError up in your code:

    • It should match the conventional importance behind the exemption.
    • A message ought to be shown with regards to the missing key alongside the missing key which should be gotten to.

    How to raise Custom Exceptions in Python?

    Python includes various inherent special cases which you can use in your program. Notwithstanding, when you’re fostering your own bundles, you may have to make your own custom special cases for increment the adaptability of your program.


    Custom Exceptions in Python
    Custom Exceptions in Python

    You can make a custom Python special case utilizing the pre-characterized class Exception:

      • def square(x):
      • on the off chance that x<=0 or y<=0:
      • raise Exception(‘x ought to be positive’)
      • return x * x

    Here, the capacity square ascertains the square of a number. We raise an Exception in the event that either the info number is negative or not.


    Disadvantages of Exception Handling :-

    However special case taking care of is extremely valuable in getting and taking care of exemptions in Python, it likewise has a few weaknesses. Some of which are as per the following—


    • It can trap just run-time mistakes.
    • At the point when you use attempt with the exception of, the program will lose some presentation and dial back a little.
    • The size of the code increments when you utilize numerous attempt, with the exception of, else lastly obstructs.
    • The idea of attempt catch may be somewhat hard to comprehend for amateurs.
    • It is valuable just in excellent blunder cases.
    • Other than these weaknesses, understanding the idea of Exception Handling can facilitate your profession as a software engineer in the realm of Python.

Python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    Conclusion :-

    Since you have now become a significant master in taking care of KeyError special cases, you can undoubtedly investigate real blunders and lessen the quantity of bugs in your code.


    Allow us to summarize what we’ve realized in the article up until this point:

  • Exemption Handling and its significance.
  • Various kinds of exemptions.
  • Python KeyError
  • Finding and raising a Python KeyError.
  • Taking care of Python KeyError.
  • Custom Exceptions.
  • Faults of Exception Handling.
  • Special cases are considered as the devices of correspondence that monitor you from possible harm. In the event that you’re clear in the comprehension of special cases, they will go about as a manual for your answers.

  • So next time when you see a Python KeyError raised, you’ll track down all the data about the area of your mistake and how to deal with that. You will effortlessly know how to get to the key utilizing the more secure get() or the more broad attempt aside from else squares to control your program’s stream all the more productively and typically.


    In any case, on the off chance that you wish to find out about blunders and exemptions, you can investigate the full documentation of Python Standard Library’s Errors and Exceptions and Exception Handling or register for the Python Certification Course at KnowledgeHut. You can likewise more deeply study Python Programming in this total Python Tutorial.

Are you looking training with Right Jobs?

Contact Us

Popular Courses

Get Training Quote for Free