0

we have following code:

class A:
    def __init__(self,x):
        self.x = x

a = A(1)
b = A(2)
c = A(2)
d = A(2)
e = A(1)
list = [a,b,c,d,e]

How to get following output?

{1:[a,e],
2:[b,c,d]
}

i was thinking of something like:

{item.x: [].append(item) for item in list}

Thanks Jano

Jan Sakalos
  • 143
  • 2
  • 11

1 Answers1

3

The defaultdict from collections is a good solution for this problem.

from collections import defaultdict

class A:
    def __init__(self,x):
        self.x = x

a = A(1)
b = A(2)
c = A(2)
d = A(2)
e = A(1)
mylist = [a,b,c,d,e]

out = defaultdict(list)

for e in mylist:
    out[e.x].append(e)
James
  • 32,991
  • 4
  • 47
  • 70