To check the given value is given key already exists in a dictionary, you can use an Inbuilt method keys()
, if
and in
operator or method has_key()
.
The in
keyword is the best way to do it.
Common Methods to Find given key already exists in a dictionary
- Inbuilt method
keys()
- Using
if
andin
- Inbuilt method
has_key()
Examples check if key exists in the dictionary
All examples will print “Exists” If present and the value of the key. Otherwise, print “Not Exists”.
1. keys()
keys() is the inbuilt method in python, it returns the list of all available keys in the dictionary. The example used an if statement and the ‘in’ operator to check if the key is present in the dictionary or not.
# Function to print check and print key
def checkKey(dict, key):
if key in dict.keys():
print("Exists, ", end=" ")
print("Value =", dict[key])
else:
print("Not Exists")
# Driver Code
dict = {'a': 100, 'b': 200, 'c': 300}
key = 'b'
checkKey(dict, key)
key = 'e'
checkKey(dict, key)
Output:
Exists, Value = 200
Not Exists
2. if and in
Simply if statement and “in” operator used to find the given key in the dictionary. in
is the intended way to test for the existence of a key in a dict
.
# Function to print check and print key
def checkKey(dict, key):
if key in dict:
print("Exists, ", end=" ")
print("value =", dict[key])
else:
print("Not Exists")
dict = {'a': 100, 'b': 200, 'c': 300}
key = 'b'
checkKey(dict, key)
key = 'e'
checkKey(dict, key)
3. has_key() (if still using Python 2.X)
Python has_key() method returns true if a key is available in the dictionary, otherwise, it returns a false. This method is removed from the Python3 version.
# Function to print check and print key
def checkKey(dict, key):
if dict.has_key(key):
print "Exists, value =", dict[key]
else:
print"Not Exists"
dict = {'a': 100, 'b': 200, 'c': 300}
key = 'b'
checkKey(dict, key)
key = 'e'
checkKey(dict, key)
Bonus: Speed test with different ways
'key' in mydict
elapsed time 1.07 secmydict.get('key')
elapsed time 1.84 secmydefaultdict['key']
elapsed time 1.07 sec
Therefore using in
or defaultdict
are recommended against get
.
Source: https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python program are in Python 3, so it may change its different from python 2 or upgraded versions.