Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If x is a value in this dict

I want to do this:

d = {1: 2, 3: 4}
if 4 in d:
    print('Aha!')

but I want to read from the values and not the keys. What's the Pythonic way to do this?

like image 821
Artur Sapek Avatar asked Feb 03 '26 15:02

Artur Sapek


2 Answers

Use values1:

d = {1: 2, 3: 4}
if 4 in d.values():
    print('Aha!')

Note that this will be much slower than a key lookup because it will potentially require inspecting all values in the dictionary. If you need to perform this operation often you might want to consider storing the values in a set.


1itervalues in Python 2

like image 126
Mark Byers Avatar answered Feb 05 '26 06:02

Mark Byers


The nature of a dictionary is that you cannot efficiently test whether or not a value is present in the way that you can test whether a key is present.

You need to iterate over the dictionary testing each value, although this can be done transparently using the code that Mark suggests. If you have large dictionaries then performance may be an issue and you may require a different data structure.

like image 29
David Heffernan Avatar answered Feb 05 '26 06:02

David Heffernan