Python KeyError 异常处理示例

1.什么是Python KeyError异常? (1. What is Python KeyError Exception?)

Python KeyError is raised when we try to access a key from dict, which doesn’t exist. It’s one of the built-in exception classes and raised by many modules that work with dict or objects having key-value pairs.

当我们尝试从dict访问一个不存在的键时,会引发Python KeyError。 它是内置的异常类之一,由许多可用于dict或具有键值对的对象的模块引发。

2.带有字典的Python KeyError (2. Python KeyError with Dictionary)

Let’s look at a simple example where KeyError is raised by the program.

让我们看一个简单的示例,其中该程序引发KeyError。

emp_dict = {'Name': 'Pankaj', 'ID': 1}

emp_id = emp_dict['ID']
print(emp_id)

emp_role = emp_dict['Role']
print(emp_role)

Output:

输出:

1
Traceback (most recent call last):
  File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/errors/keyerror_examples.py", line 6, in 
    emp_role = emp_dict['Role']
KeyError: 'Role'

3. Python KeyError异常处理 (3. Python KeyError Exception Handling)

We can handle the KeyError exception using the try-except block. Let’s handle the above KeyError exception.

我们可以使用try-except块来处理KeyError异常。 让我们处理上述KeyError异常。

emp_dict = {'Name': 'Pankaj', 'ID': 1}

try:
    emp_id = emp_dict['ID']
    print(emp_id)

    emp_role = emp_dict['Role']
    print(emp_role)
except KeyError as ke:
    print('Key Not Found in Employee Dictionary:', ke)

Output:

输出:

1
Key Not Found in Employee Dictionary: 'Role'

4.在访问字典键时避免KeyError (4. Avoiding KeyError when accessing Dictionary Key)

We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.

我们可以通过使用get()函数访问键值来避免KeyError。 如果缺少密钥,则返回None。 我们还可以指定默认值以在缺少键时返回。

emp_dict = {'Name': 'Pankaj', 'ID': 1}

emp_id = emp_dict.get('ID')
emp_role = emp_dict.get('Role')
emp_salary = emp_dict.get('Salary', 0)

print(f'Employee[ID:{emp_id}, Role:{emp_role}, Salary:{emp_salary}]')

Output: Employee[ID:1, Role:None, Salary:0]

输出: 雇员[ID:1,作用:无,薪水:0]

5.熊猫模块引发的KeyError (5. KeyError Raised by Pandas Module)

There are a few functions in Pandas DataFrame that raises KeyError exception.

Pandas DataFrame中有一些函数会引发KeyError异常。

  • rename()

     

    改名()
  • drop()

     

    下降()

6.参考 (6. References)

  • Python Exception Handling – Python try except

     

    Python异常处理– Python尝试除外
  • KeyError Wiki Page

     

    KeyError Wiki页面

翻译自: https://www.journaldev.com/33497/python-keyerror-exception-handling-examples

你可能感兴趣的:(python,深度学习,机器学习,数据分析,生成器)