Does a key exist?

EasyDictionary Programs · 18 of 94

Write a Python program to check whether a key exists in a dictionary.

Advertisement
Input
{"city": "pune", "state": "maharashtra"}, key "country"
Output
country does not exist
city exists

Approach

  1. in checks keys.

Solution

Python
d = {"city": "pune", "state": "maharashtra"}for key in ["country", "city"]:    print(key, "exists" if key in d else "does not exist")
Output
country does not exist
city exists

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Leave a Comment