BlameCapitalism
BlameCapitalism

Reputation: 93

How to check if all keys are present in list of lists element in python

Let's say there is a list of list. How can I loop through list's list 2nd element and check if all elements from other list are there?

list = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
required = [ 2, 5, 9]


if all (item in list for item[1] in required):
    log.debug('all items exist in nested list') //<- this should be printed

item[1] is wrong in example and I can't figure out how to change it.

Upvotes: 1

Views: 317

Answers (3)

folen gateis
folen gateis

Reputation: 2010

with sets

lst_set = set(x[1] for x in lst)
required=set(required)
print(lst_set&required==required)

Upvotes: 0

I&#39;mahdi
I&#39;mahdi

Reputation: 24069

Try this:

lst = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
required = [ 2, 5, 9]

chk = [any(map(lambda x: r in x, lst)) for r in required]
# [True, True, True]

if all(chk):
    print('all items exist in nested list')

Test with another required list:

lst = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
required = [ 2, 5, 11]

[any(map(lambda x: r in x, lst)) for r in required]
# [True, True, False]

Upvotes: -1

prnvbn
prnvbn

Reputation: 1027

lst = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
required = [2, 5, 9]

checker = set()

for sublist in lst:
    for elem in sublist:
        if elem in required:
            checker.add(elem)

if set(required) == checker:
    log.debug('all items exist in nested list')

Upvotes: 0

Related Questions