0

I have two classes

  • Club with property id and name
  • Student with property id, name and clubs (list)

One student can be part of multiple clubs.
One club can have multiple students

class Club:
 def __init__(self, id, name):
    self.id = id
    self.name = name

class Student:
 def __init__(self, id, name, clubs):
    self.id = id
    self.name = name
    self.clubs = clubs

I want to have a dictionary where the key is club name and value is list of students.

I have around 30 different many to many relationships in the application.

Is there a way to do it in a generic way?

martineau
  • 119,623
  • 25
  • 170
  • 301
InfoLearner
  • 14,952
  • 20
  • 76
  • 124
  • Does this answer your question? [Object of custom type as dictionary key](https://stackoverflow.com/questions/4901815/object-of-custom-type-as-dictionary-key) – buran Nov 07 '20 at 14:56
  • In addition to the link I provided it may be useful to have an attribute of `Club` that will hold all members. You can also add methods that will add club to student's clubs when added as club member as vice versa - add student to club members when club added to student's clubs – buran Nov 07 '20 at 14:59
  • On a second reading - if the key is the club name, not the club instance - that's possible given that club names are unique. It maybe better to have club ids as keys – buran Nov 07 '20 at 15:04

1 Answers1

0

A crude inverter could be like below.

def reverse(elems, array_name, i_key):
  dic = {}
  for elem in elems:
    for elem_field in elem[array_name]:
      key = elem_field[i_key]
      if key not in dic:
        dic[key] = []
      dic[key].append(elem)
  return dic

club_a = { 'name': 'a'}
club_b = { 'name': 'b'}
club_c = { 'name': 'c'}
stud_a = { 'id': 1, 'clubs': [club_a, club_b]}
stud_b = { 'id': 2, 'clubs': [club_b, club_c]}
print(reverse([stud_a, stud_b], 'clubs', 'name'))
# a: stud_a
# b: stud_a, stud_b
# c: stud_b
grodzi
  • 5,633
  • 1
  • 15
  • 15