October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Get Matching Dictionary Keys from Values in Python

Search a Python dictionary by value with items(), choose between one match and all matches, and understand when a reverse index is safe.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To find every key whose value matches a target, scan the dictionary’s key-value pairs with items():

matches = [key for key, value in data.items() if value == target]

For just the first match, use next() with a fallback. Both approaches search the dictionary’s entries; dictionaries are indexed by key, not by value.

As an Amazon Associate I earn from qualifying purchases.

Find every key with a matching value

A list comprehension returns all keys whose values compare equal to target:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
data = {"first": "ready", "second": "waiting", "third": "ready"}
target = "ready"

matches = [key for key, value in data.items() if value == target]
print(matches)  # ['first', 'third']

items() supplies each key and its value together, so the condition can compare the value while collecting the corresponding key. If multiple keys share the target value, they all appear in the result.

Return only the first matching key

If one result is enough, pass a generator expression to next():

match = next((key for key, value in data.items() if value == target), None)

This returns the first matching key in dictionary iteration order. If there is no match, it returns None. If None could itself be a key in your dictionary, use a unique sentinel so you can distinguish “no match” from a matching key:

missing = object()
match = next((key for key, value in data.items() if value == target), missing)

if match is missing:
    print("No matching key")
else:
    print(match)

Use a loop when a match needs custom handling

An explicit loop makes it straightforward to perform an action for each match, such as printing keys or applying additional conditions:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
for key, value in data.items():
    if value == target:
        print(key)

The loop visits entries in dictionary iteration order and does not stop after a match. Add break inside the if block if you want it to stop at the first one.

Choose between scanning and a reverse index

The scan-based examples are useful for occasional searches, values that may not be hashable, or dictionaries that change frequently. Each search checks entries until it finds a match or reaches the end.

If you need repeated lookups in mostly unchanged data and each value can be used as a dictionary key, build a reverse dictionary once:

value_to_key = {value: key for key, value in data.items()}
key = value_to_key.get(target)

This is convenient when values are unique. If several original keys share a value, the reverse dictionary retains only the last key encountered for that value; each assignment replaces the previous one.

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

To preserve all keys for each hashable value, build a multimap instead:

from collections import defaultdict

value_to_keys = defaultdict(list)
for key, value in data.items():
    value_to_keys[value].append(key)

matching_keys = value_to_keys.get(target, [])

Values used as reverse-dictionary keys must be hashable. Lists and dictionaries, for example, cannot be dictionary keys, so search those values with a scan instead. A reverse index also needs to be rebuilt or updated when the original dictionary changes; otherwise, it may no longer reflect the current entries.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Equality and iteration order

The examples use ==, which tests equality of the complete values. For dictionaries or other structured values, decide whether you want the whole value to match or only a particular field; for a field comparison, change the condition in the comprehension or loop.

Python guarantees dictionary insertion order starting with Python 3.7. Therefore, a first-match scan selects the earliest matching entry in that order. Updating a value for an existing key does not move the key; deleting and then reinserting it puts it at the end.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

For background on dictionary iteration, equality, hashability, and ordering, see the Python tutorial on data structures and the Python language reference on the data model.

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
PC Slower Than It Used to Be?Free scan - under a minute

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.