Python dictionary is used to store value as key value pair, unlike python list value inside a dictionary can be accessed using the key.
Simple Python Dictionary Example
d = {"one": 10, "two": 22, "three": 28}
print(d["two"]) # Output: 22
when we try to access a key value from dictionary which is not in the variable then it will throw a exception.
d = {"one": 10, "two": 22, "three": 28}
print(d["five"])
Error:
Traceback (most recent call last):
File "<string>", line 2, in <module>
KeyError: 'five'
Check if a key exists or not in a dict
To avoid this we can use the python in membership operator to check whether the key is in the dict or not
d = {"one": 10, "two": 22, "three": 28}
print("one" in d)
print("five" in d)
Output:
True
False
by checking the key is in or not will help us to avoid keyerror.
Explore Other Related Articles
Python try exception tutorial
Python classes and objects tutorial
Python Recursion Function Tutorial
Python Lambda Function Tutorial
Python If, If-Else Statements Tutorial
Python Function Tutorial
Top comments (0)