KeyError
The Python exception raised when you look up a dictionary key that does not exist.
In more detail
The error message names the missing key. Check first with in, use get(key, default) or a defaultdict, or catch KeyError when a missing key is expected.
Examples
v.get('order-id') or v.get('id')In this course: In the course, rate_for raises a KeyError naming the unknown currency, and a mismatched gateway response makes pay fail with KeyError: 'id'. Pairing pytest.raises with match checks that the error is the one you meant.Related terms
- dictionary — A Python collection that stores values under keys, written in curly brackets, such as {"tea": 250}.
- exception — An error object a program raises to stop normal flow and report that something went wrong.
- breaking change — A change that makes existing users of a program or interface stop working until they change something too.
- traceback — The report Python prints when an unhandled exception stops a program, listing the chain of calls that led there and ending with the error.
- pytest.raises — A pytest helper, used in a with block, that makes a test pass only if the code inside raises the named exception.
Taught in
- Evolving An Event Without Breaking Consumers — Apache Kafka & Event Streaming
- Dictionaries — Hands-on Python: Complete Video Course & Book
- Chapter One In One Sitting — Hands-on Python: Complete Video Course & Book
- Raising, And Writing Your Own Exception — Hands-on Python: Complete Video Course & Book
- Reading A Traceback Like A Professional — Hands-on Python: Complete Video Course & Book
- Making Failures Explain Themselves — Automated Testing, TDD & Quality Engineering
- Why Over-Mocking Breeds False Positives — Automated Testing, TDD & Quality Engineering
- The Exception Family Tree — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Dictionaries: Keys, Values And Items — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Try, Except, Else And Finally — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Functions And Exceptions Sprint — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Mock, Review And Exam Day — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Handlers, args, raise And assert — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Exception Classes Of Your Own — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Exceptions Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Twelve Traps, Mostly Objects — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep