dh762
dh762

Reputation: 2428

Compress list of objects by matching attribute in Python

I have a list of objects which I want to "compress" into a smaller list of objects based on a matching attribute (id).

class Event:
    def __init__(self, id, type, flag):
        self.id = id
        self.type = type
        self.flag = flag

eventlist = [
    Event("12345", "A", 1),
    Event("12345", "B", None),
    Event("67890", "A", 0),
    Event("67890", "B", None)]

How do I get a new list that looks like this? It should prefer defined values over None and disregard attribute type.

compressed = [
    Event("12345", 1),
    Event("67890", 0)]

edit: Better formulated question here. This can be deleted...

Upvotes: 0

Views: 79

Answers (1)

Hassan Raza
Hassan Raza

Reputation: 3165

Try this out. It should work.

eventDict={}
for e in eventlist:
     eventdict[e.id]=e.flag if e.flag is not None else eventDict[e.id]
compressed = [Event(k, None, v) for k,v in eventdict.items()]

Upvotes: 1

Related Questions