Basically the title. I'm trying to store information about duplicate objects in a list of objects, but I'm having a hard time finding anything related to this. I've devised this for now, but I'm not sure if this is the best way for what I want to do :
@dataclass
class People:
name: str = None
age: int = None
# Functions to check for duplicates (based on names)
def __eq__(self, other):
return (self.name == other.name)
def __hash__(self):
return hash(('name', self.name))
objects = [People("General", 12), People("Kenobi", 11), People("General", 15)]
duplicates, temp = [], {}
for (i, object) in enumerate(objects):
if (not object.name in temp):
temp[object.name] = {'count': 1,
'indices': [i]}
else:
temp[object.name]['count'] += 1
temp[object.name]['indices'] += [i]
for t in temp:
if (temp[t]['count'] > 1):
print(f"Found duplicates of {t}")
for i in temp[t]['indices']:
duplicates.append(objects[i])
Edit : The People
class is simple as an example. I thought about making it a dict
, but that would be more complicated than keeping track of a list of objects. I'm looking to make a new list of duplicates by name only, while keeping every other attribute/value as the original object