Many-to-many pattern possiable?

J

Jia Lu

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.
 
G

Gre7g Luterman

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
 
R

Raymond Hettinger

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){'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
 
7

7stud

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?
 
B

Bruno Desthuilliers

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top