Home > database >  Use all() function to check if all elements in list are in dictionary
Use all() function to check if all elements in list are in dictionary

Time:03-09

I have a dictionary and a list, and I want to check if all the elements in the list that start with "word" are in the dictionary.

dictionary = {'word1': '1', 'word2': '2'}
alist = ["item1", "item2", "word1", "word2"]

I would like to use all() function for this purpose. However, this all returns False, because it iterates through all the elements of the list, and returns False for items that don't start with "word".

all(item.startswith("word") and item in dictionary for item in alist)
[False, False, True, True]

How can this one-liner be adapted so it will only check the words that start with "word", and check if they are in the dictionary?

CodePudding user response:

This is very straightforward in Python. Generator expressions allow you to filter items using if:

all(item in dictionary for item in alist if item.startswith("word"))

CodePudding user response:

You can do this:

all(not item.startswith("word") or item in dictionary for item in alist)

This make sure either (1) the item doesn't start with 'word' or (2) it start with word and its in the dictionary.

  • Related