Many-to-many pattern possiable?

Gre7g Luterman hafeliel at yahoo.com
Sat May 19 13:05:40 EDT 2007


"Jia Lu" <Roka100 at gmail.com> wrote in message 
news:1179592414.652507.4110 at p77g2000hsh.googlegroups.com...

> I see dict type can do 1-to-1 pattern, But is there any method to do
> 1-to-many, many-to-1 and many-to-many pattern ?

Dict objects can do many-to-1 relationships.

Dict[Key1] = Obj
Dict[Key2] = Obj
Dict[Key3] = Obj

1-to-many relationships are more tricky and not something built-in to 
dictionaries.  You can make each value in the dictionary a list of 
associated values:

Dict[Key] = [Obj1, Obj2, Obj3]

You can even subclass dict to give it the members you like, for example:

class OneToMany(dict):
    def Add(self, Index, Value):
        V = self.get(Index, [])
        V.append(Value)
        self[Index] = V 





More information about the Python-list mailing list