339

I have the following dictionary in python:

d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}

I need a way to find if a value such as "one" or "two" exists in this dictionary.

For example, if I wanted to know if the index "1" existed I would simply have to type:

"1" in d

And then python would tell me if that is true or false, however I need to do that same exact thing except to find if a value exists.

codeforester
  • 39,467
  • 16
  • 112
  • 140
JimmyK
  • 4,801
  • 8
  • 35
  • 47

7 Answers7

483
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
True

Out of curiosity, some comparative timing:

>>> T(lambda : 'one' in d.itervalues()).repeat()
[0.28107285499572754, 0.29107213020324707, 0.27941107749938965]
>>> T(lambda : 'one' in d.values()).repeat()
[0.38303399085998535, 0.37257885932922363, 0.37096405029296875]
>>> T(lambda : 'one' in d.viewvalues()).repeat()
[0.32004380226135254, 0.31716084480285645, 0.3171098232269287]

EDIT: And in case you wonder why... the reason is that each of the above returns a different type of object, which may or may not be well suited for lookup operations:

>>> type(d.viewvalues())
<type 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>

EDIT2: As per request in comments...

>>> T(lambda : 'four' in d.itervalues()).repeat()
[0.41178202629089355, 0.3959040641784668, 0.3970959186553955]
>>> T(lambda : 'four' in d.values()).repeat()
[0.4631338119506836, 0.43541407585144043, 0.4359898567199707]
>>> T(lambda : 'four' in d.viewvalues()).repeat()
[0.43414998054504395, 0.4213531017303467, 0.41684913635253906]
mac
  • 42,153
  • 26
  • 121
  • 131
  • i have no python at hand, could you rerun the tests with 'four' instead of 'one' ? – soulcheck Nov 21 '11 at 16:55
  • 2
    it wasn't necesarry after all, unless run on bigger dict. I guess overhead in values() is caused by copying the value list and in viewvalues() by maintaining the view alive. – soulcheck Nov 21 '11 at 17:12
  • 2
    Given the small size of `d`, the timings are effectively meaningless. In Python 3, `dict.values()` is a dictionary view, by default, and `dict.itervalues()` and `dict.viewvalues()` are gone. You could re-test this (with a larger dictionary) and use `list(d.values())` to get the Python 2 behaviour, and `iter(d.values())` to get the `dict.itervalues()` behaviour, but because both those versions require a global lookup and call, they'll absolutely be slower. Both do extra work that's not needed. – Martijn Pieters Aug 15 '19 at 12:02
51

In Python 3, you can use

"one" in d.values()

to test if "one" is among the values of your dictionary.

In Python 2, it's more efficient to use

"one" in d.itervalues()

instead.

Note that this triggers a linear scan through the values of the dictionary, short-circuiting as soon as it is found, so this is a lot less efficient than checking whether a key is present.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 4
    I know this is a *really* old answer, but just wanted to note that in Python 3 it is `values()` and not `itervalues()`. I went into idiot mode for a while and tried to get `itervalues()` working in Python 3, before realising I'm an idiot. –  Dec 08 '20 at 06:14
  • 3
    @digitalformula that was exactly the trap i stepped into too, thank you very much – procra Dec 10 '20 at 08:01
32

Python dictionary has get(key) function

>>> d.get(key)

For Example,

>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> d.get('3')
'three'
>>> d.get('10')
None

If your key does not exist, then it will return None value.

foo = d[key] # raise error if key doesn't exist
foo = d.get(key) # return None if key doesn't exist

Content relevant to versions less than 3.0 and greater than 5.0.

micstr
  • 5,080
  • 8
  • 48
  • 76
Shameem
  • 2,664
  • 17
  • 21
11

Use dictionary views:

if x in d.viewvalues():
    dosomething()..
soulcheck
  • 36,297
  • 6
  • 91
  • 90
5

Different types to check the values exists

d = {"key1":"value1", "key2":"value2"}
"value10" in d.values() 
>> False

What if list of values

test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6']}
"value4" in [x for v in test.values() for x in v]
>>True

What if list of values with string values

test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6'], 'key5':'value10'}
values = test.values()
"value10" in [x for v in test.values() for x in v] or 'value10' in values
>>True
  • Don't use `value in [... list comprehension over sequence ...]`, use `any(value in sequence ...)`, to avoid creating a list object you don't use for anything else, and to short-circuit when the value has been found. – Martijn Pieters Aug 15 '19 at 12:23
1

You can use this:

d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
print("one" in d.values)

Or:

print(any([True for i,j in d1.items() if j == "one"]))
-2

In Python 3 you can use the values() function of the dictionary. It returns a view object of the values. This, in turn, can be passed to the iter function which returns an iterator object. The iterator can be checked using in, like this,

'one' in iter(d.values())

Or you can use the view object directly since it is similar to a list

'one' in d.values()
Reed Richards
  • 4,178
  • 8
  • 41
  • 55
  • 2
    There is *no point* in using `iter()` on a dictionary view; `in` will already use the object as an iterable (the type doesn't implement a dedicated `__contains__` method). The only difference between `'one' in iter(d.values())` and `'one in d.values()` is that you made Python do extra work (paying the cost of a global lookup for `iter`). – Martijn Pieters Aug 15 '19 at 12:20