user16655
user16655

Reputation: 1941

Key with multiple values - check if value is in dictionary python

I have a dictionary that has a list of multiple values stored for each key. I want to check if a given value is in the dictionary, but this doesn't work:

if 'the' in d.values():
    print "value in dictionary"

Why doesn't it work with multiple values stored as a list? Is there any other way to test if the value is in the dictionary?

Upvotes: 1

Views: 8790

Answers (6)

Rohit Chatterjee
Rohit Chatterjee

Reputation: 3107

I like to write

if 0 < len([1 for k in d if 'the' in d[k]]):
    # do stuff

or equivalently

if 0 < len([1 for _,v in d.iteritems() if 'the' in v]):
    # do stuff

Upvotes: 0

thiruvenkadam
thiruvenkadam

Reputation: 4250

If you just want to check whether a value is there or not without any need to know the key it belongs to and all, you can go with this:

if 'the' in str(d.values())

Or for a one-liner, you can use the filter function

if filter(lambda x: 'eggs' in x, d.values()) # To just check
filter(lambda x: 'eggs' in d[x] and x, d) # To get all the keys with the value

Upvotes: 0

Onedot618
Onedot618

Reputation: 273

You can iterate over the dictionary. If your dictionary looks like follows:

my_dictionary = { 'names': ['john', 'doe', 'jane'], 'salaries': [100, 200, 300] }

Then you could do the following:

for key in my_dictionary:
    for value in my_dictionary[key]:
        print value

You can naturally search instead of print. Like this:

for key in my_dictionary:
    for value in my_dictionary[key]:
        if "keyword" in value:
            print "found it!"

There is probably a shorter way to do this, but this should work too.

Upvotes: 1

felipsmartins
felipsmartins

Reputation: 13549

It should be pretty simple:

>>> d = { 'a': ['spam', 'eggs'], 'b': ['foo', 'bar'] }
>>> 'eggs' in d.get('a')
True

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

d.values() usually stores the values in list format. So you need to iterate through the list contents and check for the substring the is present or not.

>>> d = {'f':['the', 'foo']}
>>> for i in d.values():
        if 'the' in i:
            print("value in dictionary")
            break


value in dictionary

Upvotes: 4

JiaJie999
JiaJie999

Reputation: 118

Your values is a list!

for item in d.values():
    if 'the' in item:
        print "value in dictionary"

Upvotes: 1

Related Questions