Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection in sets

I have my_dict with sets as values and I have x which is also a set.

I need to return list with set from my dict which contain all numbers in x. If set in my_dict does not contain all numbers in x I do not want to return it.

I want to use intersection (&) but it returns all the sets in my_dict.

my_dict = {1: {1,2,3,4,5},

       2: {1,2,3,7,8},

       3: {1,2,3,4}

       }

x = {1,2,5}
new_list = []


for i in my_dict:
   if my_dict[i] & x:
        new_list.append(i)
print(new_list)

Output:

[1, 2, 3]

I need to receive [1] instead of [1, 2, 3]

like image 399
Dmitriy_kzn Avatar asked Mar 05 '26 07:03

Dmitriy_kzn


2 Answers

When intersection becomes x that means all values in x are present in the set in dictionary.

for i in my_dict:
     if (my_dict[i] & x)==x:
         new_list.append(i)
print(new_list)

Edit: as suggested in the comments below you can also do

for i in my_dict:
     if x.issubset(my_dict[i]):
         new_list.append(i)
print(new_list)
like image 114
Rajan Chauhan Avatar answered Mar 06 '26 21:03

Rajan Chauhan


I suggest you use the set.issuperset method, rather than using the & operator. Why combine several operators when a method exists to do exactly what you want?

new_list = []
for i in my_dict:
    if my_dict[i].issuperset(x):
        new_list.append(i)

Note that I'd normally write this with a list comprehension:

newlist = [key for key, value in my_dict.items() if value.issuperset(x)]
like image 28
Blckknght Avatar answered Mar 06 '26 20:03

Blckknght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!