In python is it possible to compare all objects in the following structure
I have a dictionary of lists and each list has objects in it e.g.
[
[object1,object2,object3],
[object4,object5,object6],
[object7,object8,object9],
]
I want to compare all objects by a attribute in each list to each other and identify what objects are not in each list.
Based on the feedback please see an example below
from collections import defaultdict
from pprint import pprint
class mytest:
def __init__(self, no, description):
self.no = no
self.description = description
data = []
x = mytest(1,'test1')
x2 = mytest(2,'test1')
x3 = mytest(1,'test2')
x4 = mytest(2,'test2')
x5 = mytest(3,'test2')
x6 = mytest(1,'test3')
x7 = mytest(2,'test3')
x8 = mytest(4,'test3')
data.append(x)
data.append(x2)
data.append(x3)
data.append(x4)
data.append(x5)
data.append(x6)
data.append(x7)
data.append(x8)
groups = defaultdict(list)
for obj in data:
groups[obj.description].append(obj)
new_list = groups.values()
#i want to find out what items are not in each list
for list in new_list:
pprint(list)
#example x8 = mytest(4,'test3') is only in one of the list so is missing from list 1 and 2
hopefully this helps
I think this is what you're looking for. We create a set of the possible values of obj.no
and then use the set difference operator ( using -
on two sets, to get the elements missing).
# Get a set of all the no. values present in the data.
combined_set_of_values = set([item.no for item in data])
# Get the sets of obj.no values grouped by description.
for obj in data:
groups[obj.description].append(obj.no)
new_list = groups.values()
# Print the list, and the elements missing from that list
for list in new_list:
print("Values in list:")
print(list)
# Use set difference to see what's missing from list.
print("Missing from list:")
print(combined_set_of_values - set(list))
This gives an output of:
Values in list:
[1, 2]
Missing from list:
{3, 4}
Values in list:
[1, 2, 3]
Missing from list:
{4}
Values in list:
[1, 2, 4]
Missing from list:
{3}