Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

How to Check Whether a Key Exists in a Python Dictionary

Use `key in dictionary` to test key presence. Choose `get()` for a fallback, or `dictionary[key]` when a missing key should raise `KeyError`.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use key in dictionary to check whether a Python dictionary contains a key. It returns True or False and checks keys, not values. Choose get() when you want a fallback value, or bracket lookup when a missing key should raise an error.

Check for a key with in

Python’s built-in mapping membership test is key in d. It returns True if the dictionary has that key and False otherwise, as documented in the Python 3.14.8 built-in types reference.

settings = {"theme": "dark", "timeout": None}

if "theme" in settings:
    print("theme is present")

if "timeout" in settings:
    print("timeout is present, even though its value is None")

The test checks for keys. To check whether a value appears in a dictionary, use value in d.values() instead.

Choose between in, get(), and bracket lookup

What you need Use What happens if the key is missing
Test presence and branch on the result key in d Returns False
Read a value and allow it to be absent d.get(key, default) Returns the supplied default; if omitted, returns None
Read a required value d[key] Raises KeyError for a missing key in an ordinary dictionary

The Python reference documents these behaviors for in, get(), and subscription in its dictionary documentation. Use the operation whose missing-key behavior matches what your code should do.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use get() for a fallback

For example, this uses 3 when the retries key is absent:

retries = settings.get("retries", 3)

If you leave out the second argument, get() returns None when the key is missing. Unlike d[key], it does not raise KeyError for that case.

Use brackets when the value is required

Use d[key] when missing data should be treated as an error. In an ordinary dictionary, requesting an absent key raises KeyError, which can expose invalid or incomplete input rather than silently substituting a fallback.

Distinguish a missing key from a value of None

settings.get("timeout") returns None both when "timeout" is absent and when it is present with the value None. If those cases mean different things, test membership separately:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if "timeout" in settings:
    timeout = settings["timeout"]  # The value may intentionally be None.
else:
    timeout = 30

Alternatively, give get() a unique sentinel so a stored None is distinguishable from absence:

missing = object()
timeout = settings.get("timeout", missing)

if timeout is missing:
    timeout = 30
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep dictionary key behavior in mind

Keys must be hashable

Dictionary keys must be hashable. Common immutable values such as strings and numbers can be keys; lists and dictionaries cannot normally be used as keys. See the Python built-in types reference.

Equal keys can refer to the same entry

Python treats values that compare equal as interchangeable dictionary keys. For example, 1, 1.0, and True can address the same entry. This behavior is described in the Python 3.14.7 built-in types reference.

Insertion order does not affect membership

Dictionaries preserve insertion order, guaranteed starting with Python 3.7. That ordering affects iteration, not whether key in d finds a key; the Python documentation treats these as separate behaviors.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Custom dictionary subclasses may alter bracket lookup

A dict subclass can define __missing__(), which may be called by bracket lookup when a key is absent. The Python reference notes that other operations do not invoke __missing__(). For a custom mapping or subclass, check its documented behavior rather than assuming every lookup acts exactly like an ordinary dictionary; see the reference for dictionary types.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.