The in operator

user = {"name": "Ana", "age": 30}
if "name" in user:
    print("Key is present")

This reads almost like English and is the idiom experienced Python developers reach for first.

Use .get() to read safely

age = user.get("age")          # 30
city = user.get("city", "N/A") # "N/A"

get() returns the value if the key exists, or a default (here "N/A") instead of raising a KeyError.

Check that a key is missing

if "city" not in user:
    print("No city set")

not in reads naturally when you want to act on a missing key.

Which method should you use?

  • in — when you only need a yes/no answer.
  • .get() — when you want the value and a safe fallback in one step.
  • Avoid has_key() — it was removed in Python 3.

Frequently asked questions

Does "x" in my_dict check keys or values?

Keys only. To search the values, use "Ana" in my_dict.values() instead.

Why avoid try/except KeyError just to check a key?

It works, but in and .get() are clearer and faster for a simple presence check. Save try/except for cases where a missing key is a genuine error.

Want to master dictionaries from the ground up? Start with our beginner-friendly Python course.