Method for judging whether key exists by dict of python

  • 2021-08-17 00:37:40
  • OfStack

When you learn the dictionary in python, you will find that there is no special order in the dictionary, but they are all stored under a specific key. What is key? In fact, key is the key in python dictionary, which can be a number or a string, and can store any type of object. Do you know how to judge the existence of key in the dictionary? The following site will introduce you to python, to determine whether there is key dictionary two methods.

Method 1: Use your own function to implement it


dict = {'a': {}, 'b': {}, 'c': {}}
print(dict.__contains__("b"))      Return to: True
print(dict.__contains__("d"))      Return to: False

Method 2: Use the in method


# Generate 1 A dictionary 
d = {'a':{}, 'b':{}, 'c':{}}
# Prints the return value, where d.keys() Is to list all the dictionary key
print 'a' in d.keys()
print 'a' in d

Extension of knowledge points:

Two methods for python to judge whether key exists in dict

If key does not exist, dict will report an error:


>>> d['Thomas']
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
KeyError: 'Thomas'

To avoid the error that key does not exist, there are two ways. 1 is to judge whether key exists through in:


>>> 'Thomas' in d
False

2 is the get method provided by dict. If key does not exist, you can return None or value specified by yourself:


>>> d.get('Thomas')
>>> d.get('Thomas', -1)
-1

Note: When None is returned, the interactive command line of Python does not display the results.

The above is the dict of python to judge whether key exists in detail. For more information about how to judge whether key exists in python, please pay attention to other related articles on this site!


Related articles: