Meliande
Meliande

Reputation: 13

How to check if a list is contained within any of the keys of a dictionary in python?

Hellos guys, I'm trying to check if a all elements of a list are contained in any of the keys of a dictionary as long as they are on the same key, for example;

dict = {1:{1,2,3,4,5,6},2:{10,2,9,8,5,7},3:{11,9,3,13},4:{12,8,4,13,14},}

I have those 3 list

[1,2,9],[2,9,8],[9,8,12]

Only the second list should return true as it's values are contained within key 2 of the dictionary the others should all return false

Can someone help find out a way to do it?

Upvotes: 0

Views: 72

Answers (1)

python_user
python_user

Reputation: 7083

You can use a nested list comprehension with any and set operations.

d = {1:{1,2,3,4,5,6},2:{10,2,9,8,5,7},3:{11,9,3,13},4:{12,8,4,13,14},}

to_check = [1,2,9],[2,9,8],[9,8,12]

res = [any(j.issuperset(i) for j in d.values()) for i in to_check]

Output

[False, True, False]

Upvotes: 1

Related Questions