Explain Codes LogoExplain Codes Logo

How to check if a value exists in a dictionary?

python
dataframe
pandas
list-comprehensions
Alex KataevbyAlex Kataev·Feb 15, 2025
TLDR

Check if a key exists in a dict with:

'key' in my_dict

Check if any value exists:

"value" in my_dict.values()

Deep Dive into value checking

In the constellation of Python dictionaries, let's look at the space-savvy ways of tracking the existence of a value. There's more than one way to skin this extraterrestrial entity. 🐱‍🚀

Neat 'n' easy: the 'in' operator

The most straightforward approach is the in operator with dict.values(). It's as easy as pie.

if "I'm Looking For This" in my_dict.values(): print("Found ya!")

Performance enthusiasts, rejoice! dict.viewvalues()

To cater to your need for speed, in terms of performance, especially for beefy dictionaries, opt for dict.viewvalues() in Python 3. No lists were harmed in checking this value.

if "Looking Fast" in my_dict.viewvalues(): print("Ey! No lists were inadequate here!")

Time it! Compare like a boss

Any claims of efficiency should be road-tested. Use timeit for a showdown unlike anything you've seen before.

import timeit # Take a look at this dictionary, as large as my grandmother's sweet collection big_dict = {i:i for i in range(1000)} # Time it, because time flies, but you're the pilot! timer = timeit.timeit(lambda: 999 in big_dict.values(), number=1000) print(f"Every second counts! The operation took: {timer} seconds")

Caution! Value not found? Behold, dict.get()

To avoid a code meltdown if the value is not found, use the defensive dict.get() method, which conveniently returns None if the key doesn't exist.

if not my_dict.get("non-existent"): print("Playing it safe, huh? Value doesn't exist!")

Nested structures: Not paranoid if they're really nested

If your dictionary holds nested values, list comprehensions will save the day!

nested_dict = {1: [2,3], 2: [3,4], 3: [4,5]} if any("Need to find this deep" in val for val in nested_dict.values()): print("Dude, I dug deep and found your value!")

Advanced Value Checking Maneuvers

This isn't just Checking for values in Dictionaries 101. Welcome to the master's class.

Vintage Python: bow before dict.itervalues()

If by some chance you're playing with Python 2, go for the classic dict.itervalues(). It can provide the upper hand for lookups.

if "hope you're not actually using Python 2" in my_dict.itervalues(): print("Value exists, but upgrade to Python 3 - we've got `f-strings`!")

Types matter: a tale of dict.values()

Note that the dict.values() hands out a list-like object, not an actual list. That might have performance implications when iterating.

Real-time tracking with Dictionary views

For those who like dynamic checks that reflect any chances to the dictionary in real-time, dictionary views are your pal.