How to check if Key Exists in Python Dictionary?


To check if a Python Dictionary contains a specific key or not you can make use of the if statement with a in keyword,


Example:
# Python Dictionary containing
# names of cities

def check_for_key(cities,city_name):
  if city_name in cities:
    print("City {} is available in dictionary cities..".format(city_name))
  else:
    print("City {} is not available in dictionary cities..".format(city_name))

cities = {'Tokyo','Paris','New York', 'Mumbai', 'London'}

check_for_key(cities,'London')
check_for_key(cities,'Austin')
Output:

City London is available in dictionary cities..
City Austin is not available in dictionary cities..


Check Key in Python Dictionary
-


Have Questions? Post them here!

Topics Coverage:


🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.

Follow Us: GitHub | Facebook | Twitter | Instagram