jhancock532
jhancock532

Reputation: 402

How to test/search for values in dictionaries

I'm trying to check whether a specific value in a dictionary is present. It seems that with keys, a simple if 'x' in 'dictionary' statement works, yet not for values.

dictionary = {
    'First': '1',
    'Second': '2',
    'Third': '3'
}

if 'First' in dictionary:
    print('First is here')

if '1' in dictionary:
    print('1 is here')

So the obvious logical error is that the output only reads:

First is here

Any advice would be much appreciated, thank you.

Upvotes: 1

Views: 62

Answers (2)

user2555451
user2555451

Reputation:

If you want to access the dictionary's values, you need to call dict.values:

if '1' in dictionary.values():

It is not necessary to call dict.keys however:

if 'First' in dictionary.keys():

because the in operator iterates over the dictionary, which yields its keys.

Upvotes: 3

Dan Lenski
Dan Lenski

Reputation: 79792

Read the docs on dict. The key in d operator on a dictionary looks for a key in the dict's keys, not its values.

To look in the values, use value in d.values().

Also, this is a less efficient O(size of dict) operation. If you're constantly searching for values, you should generally use a different data structure (maybe a sorted list depending on the exact use case).

Upvotes: 2

Related Questions