tags:

views:

393

answers:

3

hi i am a newbie to Python

I need to use multi-map to store my data, i.e.,

a = multidict()
a[1] = 'a'
a[1] = 'b'
a[2] = 'c'

print(a[1])  # prints: ['a', 'b']
print(a[2])  # prints: ['c']

is there any suggestions? can anyone provide some keywords so that i can google?

+12  A: 

Such a thing is not present in the standard library. You can use a defaultdict though:

>>> from collections import defaultdict
>>> md = defaultdict(list)
>>> md[1].append('a')
>>> md[1].append('b')
>>> md[2].append('c')
>>> md[1]
['a', 'b']
>>> md[2]
['c']

(Instead of list you may want to use set, in which case you'd call .add instead of .append.)


As an aside: look at these two lines you wrote:

a[1] = 'a'
a[1] = 'b'

This seems to indicate that you want the expression a[1] to be equal to two distinct values. This is not possible with dictionaries because their keys are unique and each of them is associated with a single value. What you can do, however, is extract all values inside the list associated with a given key, one by one. You can use iter followed by successive calls to next for that. Or you can just use two loops:

>>> for k, v in md.items():
...     for w in v:
...         print("md[%d] = '%s'" % (k, w))
... 
md[1] = 'a'
md[1] = 'b'
md[2] = 'c'
Stephan202
A: 

I do not clearly understand the semantics of your example

a[1] = 'a'
a[1] = 'b' #??

Is second line a[1] = 'b' supposed to replace the element at [1]. If yes, then you need to use dictionary. If not - you need to use dictionary of lists (as already suggested)

BostonLogan
Read what a multi-map is: http://www.cplusplus.com/reference/stl/multimap/
Casebash
+4  A: 

is there any suggestions? can anyone provide some keywords so that i can google?

Since you asked... how about googling "multimap python"? Third hit: http://code.activestate.com/recipes/576835/

Thomas