简体   繁体   中英

Check if a word is in a list that is a value of a dictionary

I'm trying to check if a word is in a list that is a value of a dictionary. For example i want to check if 'noodles' is in: {1:['hello', 'hallo', 'salut', 'ciao', 'hola'], 2:['eggs', 'noodles', 'bacon']}

I tried with:

element = 'noodles'
element in myDict.values()

But i get: False

Your code checks if element ( 'noodles' ) is a value in the dictionary, and it isn't (the values are lists).

You need to check if element is inside every list.

If you don't care for the key:

print(any(element in value for value in myDict.values()))

If you want to know the key (this will print a list of matching keys):

print([key for key, value in myDict.items() if element in value])

But , generally speaking, if you find yourself having to loop over a dictionary over and over again, you either made a bad choice for what are the keys, or using the wrong data structure altogether.

The dict.values() call here returns an iterable of lists. You'll need to flatten the returned iterable first, to test directly:

from itertools import chain

element = 'noodles'
print(element in chain.from_iterable(my_dict.values())) # -> True

You should use a function here , You can do with pure python without importing any module or making it more complicated :

Data:

Your_dict={1:['hello', 'hallo', 'salut', 'ciao', 'hola'], 2:['eggs', 'noodles', 'bacon']}
your_word='noodles'

code:

def find(dict_1,word):
    for words in dict_1.values():
        if word in words:
            return True
    else:
        return False




print(find(Your_dict,your_word))

output:

True

One line solution without any for loop or module :

Just for fun

print(list(map(lambda x:x if your_word in x else None,Your_dict.values())))

output:

[None, ['eggs', 'noodles', 'bacon']]
myDict = {1: ['hello', 'hallo', 'salut', 'ciao', 'hola'], 2: ['eggs', 'noodles', 'bacon']}
element = 'noodles'
[print(True) if element in value else None for value in myDict.values()]

# It will give true if it is present

You can use any() on a generator-expression :

any("noodles" in v for v in d.values())

which, in this case, gives:

True

why?

Well d.values() returns an iterables of all the values in the dictionary d . So in this case, the result of d.values() would be:

dict_values([['hello', 'hallo', 'salut', 'ciao', 'hola'], ['eggs', 'noodles', 'bacon']])

We then went to check if the string "noodles" is in any of these values ( lists ) .

This is really easy / readable to do. We just want to create a generator that does exactly that - ie return a boolean for each value indicating whether or not "noodles" is in that list .

Then, as we now have a generator , we can use any() which will just return a boolean for the entire generator indicating whether or not there wer any Trues when iterating through it. So what this means in our case is if "noodles" is in any of the values .

You should go with loop.It will work definitely.This is tested code.

element = 'noodles'
for i in dict1.values():
    if(element in i):
        print(True)
        count+=1
print(count)

Count will count the number of occurrence of your element.If it is 0 then element is not available in dictionary's values and if it is more than 0 then it is available in dictionary's values.Count is just for your reference.

You can use dict.items() :

s = {1:['hello', 'hallo', 'salut', 'ciao', 'hola'], 2:['eggs', 'noodles', 'bacon']}
element = 'noodles'
if any(element in b for a, b in s.items()):
   pass

myDict.values() will return a list of lists and not something you can ask x in y on, you won't be able to avoid a loop in some flavor similar to Python search in lists of lists

...unless that is you find this time consuming and decide to keep some sort of hash to contain all elements inside the lists contained in myDict.values. Note though that this will take O(len(l)) for each insertion of l into the dictionary.

In my case I needed to check if the word exists in either keys or values and here is a simple solution. (It may help someone)

if 'noodle' in str(myDict):
    True
else:
    False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM