Search code examples
pythonlist-comprehensionlist-comparison

Using list compreshension with a list of dictionaries


I have a list of dictionaries (LDICT) and a list of strings (LS). I would like to check to make sure that the items in LS are not the keys in any of the dictionaries in LDICT. If they are, I would like to remove the item from LS.

I've figured out a way to do this with for loops but it is ugly and I am struggling to understand how I can achieve this using list comprehension.

See code below for the example using for loops:

for item in LDICT:
    for k, v in item.iteritems():
        if k in LS:
            LS.remove(k)

Solution

  • Use any() to check each word in LS:

    [k for k in LS if not any((k in t) for t in LDICT)]