By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,173 Members | 796 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,173 IT Pros & Developers. It's quick & easy.

Many-to-many pattern possiable?

P: n/a
Hi all

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 ? What about using some
Serialized objects?

Thanks.

May 19 '07 #1
Share this Question
Share on Google+
4 Replies


P: n/a
"Jia Lu" <Ro*****@gmail.comwrote in message
news:11********************@p77g2000hsh.googlegrou ps.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
May 19 '07 #2

P: n/a
On May 19, 9:33 am, Jia Lu <Roka...@gmail.comwrote:
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 ?
>>mm = {'a': ['A', 'B', 'C'], 'c': ['C', 'D', 'E'], 'b': ['A', 'D']}
>># Now, invert the relation
mmr = {}
for k, seq in mm.items():
.... for elem in seq:
.... mmr.setdefault(elem, []).append(k)
>>mmr
{'A': ['a', 'b'], 'C': ['a', 'c'], 'B': ['a'], 'E': ['c'], 'D': ['c',
'b']}

What about using some
Serialized objects?
from pickle import loads, dumps
d = dict(a=dumps(someobj), b=dumps(anotherobj))
obj = loads(d['a'])
Raymond

May 19 '07 #3

P: n/a
On May 19, 10:33 am, Jia Lu <Roka...@gmail.comwrote:
Hi all

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 ?
How about:

one_to_many = {"a":[10, "red", 2.5]}

many_to_1 = {("red", 2.5, 3):"hello"}

many_to_many = {("red", 2.5, 3):[10, 20, 30]}

In reality, everything is mapped 1-1. I wonder if there is a computer
language where that isn't the case?

May 19 '07 #4

P: n/a
Jia Lu a écrit :
Hi all

I see dict type can do 1-to-1 pattern, But is there any method to do
1-to-many,
a dict of lists
many-to-1
What's the difference with 1-n ?
and many-to-many pattern ?
As usual, using an intermediate dict.
What about using some
Serialized objects?
What for ?

Anyway, if you're after a relational model, better to use some
relational db, possibly with SQLAlchemy on top.
May 20 '07 #5

This discussion thread is closed

Replies have been disabled for this discussion.