Matt Takao
Matt Takao

Reputation: 3006

Python: checking if an item is in a dictionary. Key OR value

I'm trying to check if a dictionary has a certain value in its keys as well as its values with just one command instead of having to OR two searches. I.e.

'b' in d.keys()
'b' in d.keys() or 'b' in d.values()

Searching the internet with these terms has returned nothing but instructions on how to do search just keys or just values.

d = {'a':'b'}
d.items()         ## this is the closest thing I could find to all the items
'b' in d.items()  ## but this returns false

Upvotes: 0

Views: 2433

Answers (2)

viraptor
viraptor

Reputation: 34205

There's no single function to do this. You'll have to either do (without keys() is faster):

'b' in d or 'b' in d.values()

or some kind of loop over items:

for i in d.items():
    if 'b' in i:
        return True
return False

or:

any(('b' in i) for i in d.items())

PS. It also points at a bad design. Dictionaries are cool for key lookups, because they're fast at that. If you check both keys and values, you're just looking through all the stored items anyway. (and it shows you're not even sure which side you're looking at) I'd suggest checking if maybe some combination of sets and dicts is better suited for what you want to do.

Upvotes: 2

John
John

Reputation: 13709

The problem with d.items() is that it returns a list of key/value pairs that are represented as tuples so 'b' will not be in [('a', 'b')].

all_items = d.keys() + d.values()
'b' in all_items

Upvotes: 0

Related Questions