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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap