Python check if key exists in dictionary | key(), if & in, has_key()

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 and in
  • Inbuilt method has_key()

Examples check if key exists in 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. In the example used an if statement and the ‘in’ operator to check if the key is present in the dictionary or not.

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.

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.

Bonus: Speed test with different ways

  • 'key' in mydict elapsed time 1.07 sec
  • mydict.get('key') elapsed time 1.84 sec
  • mydefaultdict['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.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.