473,406 Members | 2,843 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Python multimap

Recently had a need to us a multimap container in C++. I now need to
write equivalent Python code. How does Python handle this?

k['1'] = 'Tom'
k['1'] = 'Bob'
k['1'] = 'Joe'
....

Same key, but different values. No overwrites either.... They all must
be inserted into the container

Thanks,
Brad
Aug 27 '08 #1
12 7420
On Aug 27, 9:35*am, brad <byte8b...@gmail.comwrote:
Recently had a need to us a multimap container in C++. I now need to
write equivalent Python code. How does Python handle this?

k['1'] = 'Tom'
k['1'] = 'Bob'
k['1'] = 'Joe'
...

Same key, but different values. No overwrites either.... They all must
be inserted into the container

Thanks,
Brad
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>k = {}
k['1'] = []
k['1'].append('Tom')
k['1'].append('Bob')
k['1'].append('Joe')

k['1']
['Tom', 'Bob', 'Joe']
>>>
Aug 27 '08 #2
brad wrote:
Recently had a need to us a multimap container in C++. I now need to
write equivalent Python code. How does Python handle this?

k['1'] = 'Tom'
k['1'] = 'Bob'
k['1'] = 'Joe'
...

Same key, but different values. No overwrites either.... They all must
be inserted into the container

Thanks,
Brad
I don't know if this is exactly equivalent, but what about using a
defaultdict like this?
>>from collections import defaultdict
k = defaultdict(list)
k['1'].append('Tom')
k['1'].append('Bob')
k['1'].append('Joe')
k['1']
['Tom', 'Bob', 'Joe']
--
Aug 27 '08 #3
brad wrote:
Recently had a need to us a multimap container in C++. I now need to
write equivalent Python code. How does Python handle this?

k['1'] = 'Tom'
k['1'] = 'Bob'
k['1'] = 'Joe'
....

Same key, but different values. No overwrites either.... They all must
be inserted into the container
Subclassing the builtin dict?

class d(dict):
def __setitem__(self, item, value):
if not item in self: super(d, self).__setitem__(item, [])
self[item].append(value)
>>D = d()
D[1] = "Hello"
D[1] = "World!"
D[1]
['Hello', 'World!']

Thanks,
Brad
Michele
Aug 27 '08 #4
Mike Kent wrote:
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>k = {}
k['1'] = []
k['1'].append('Tom')
k['1'].append('Bob')
k['1'].append('Joe')

k['1']
['Tom', 'Bob', 'Joe']
There is only one '1' key in your example. I need multiple keys that are
all '1'. I thought Python would have something built-in to handle this
sort of thing.

I need a true multimap:

k['1'] = 'Tom'
k['1'] = 'Tommy'

without Tommy overwriting Tom and without making K's value a list of
stuff to append to. That's still just a regular map.
Aug 27 '08 #5
brad wrote:
There is only one '1' key in your example. I need multiple keys that are all
'1'. I thought Python would have something built-in to handle this sort of
thing.

I need a true multimap ... without making K's value a list of stuff
to append to.
That's what a multimap is. If you really need the syntactic sugar,
it's simple to implement:

class multidict(dict):
def __setitem__(self, key, value):
try:
self[key].append(value)
except KeyError:
dict.__setitem__(self, key, [value])

-Miles
Aug 27 '08 #6
On Aug 27, 12:52*pm, brad <byte8b...@gmail.comwrote:
Mike Kent wrote:
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>k = {}
k['1'] = []
k['1'].append('Tom')
k['1'].append('Bob')
k['1'].append('Joe')
>>k['1']
['Tom', 'Bob', 'Joe']

There is only one '1' key in your example. I need multiple keys that are
all '1'. I thought Python would have something built-in to handle this
sort of thing.

I need a true multimap:

k['1'] = 'Tom'
k['1'] = 'Tommy'

without Tommy overwriting Tom and without making K's value a list of
stuff to append to. That's still just a regular map.
I don't understand what a multimap does that a map of lists doesn't do.
Aug 27 '08 #7
castironpi wrote:
I don't understand what a multimap does that a map of lists doesn't do.
It counts both keys individually as separate keys. The Python workaround
does not... see examples... notice the key(s) that are '4'

Python output (using the k = [] idea):

Key: 4 Value: [[13, 'Visa'], [16, 'Visa']]
Key: 51 Value: [16, 'MC']
Key: 65 Value: [16, 'Discover']
Key: 2131 Value: [15, 'JCB']
Key: 300 Value: [14, 'Diners CB']
Key: 301 Value: [14, 'Diners CB']
Key: 302 Value: [14, 'Diners CB']
Key: 303 Value: [14, 'Diners CB']
Key: 304 Value: [14, 'Diners CB']
Key: 305 Value: [14, 'Diners CB']
Key: 35 Value: [16, 'JCB']
Key: 34 Value: [15, 'Amex']
Key: 55 Value: [16, 'MC or Diners US and CA']
Key: 36 Value: [14, 'Diners Intl']
Key: 37 Value: [15, 'Amex']
Key: 1800 Value: [15, 'JCB']
Key: 54 Value: [16, 'MC']
Key: 6011 Value: [16, 'Discover']
Key: 52 Value: [16, 'MC']
Key: 53 Value: [16, 'MC']
Key: 385 Value: [14, 'Diners CB']
21 is the size of the dict

A C++ multimap

Key: 1800 Value: JCB 15
Key: 2131 Value: JCB 15
Key: 300 Value: Diners_Club 14
Key: 301 Value: Diners_Club 14
Key: 302 Value: Diners_Club 14
Key: 303 Value: Diners_Club 14
Key: 304 Value: Diners_Club 14
Key: 305 Value: Diners_Club 14
Key: 34 Value: American_Express 15
Key: 35 Value: JCB 16
Key: 36 Value: Diners_Club 14
Key: 37 Value: American_Express 15
Key: 385 Value: Diners_Club 14
Key: 4 Value: Visa 16
Key: 4 Value: Visa 13
Key: 51 Value: MasterCard 16
Key: 52 Value: MasterCard 16
Key: 53 Value: MasterCard 16
Key: 54 Value: MasterCard 16
Key: 55 Value: MasterCard 16
Key: 6011 Value: Discover 16
Key: 65 Value: Discover 16
22 is the size of the multimap
Aug 27 '08 #8
Miles wrote:
That's what a multimap is.
iirc, a C++ multimap provides a flat view of the data, so you need to
provide custom enumeration and iteration methods as well.

</F>

Aug 27 '08 #9
On Aug 27, 1:38*pm, brad <byte8b...@gmail.comwrote:
castironpi wrote:
I don't understand what a multimap does that a map of lists doesn't do.

It counts both keys individually as separate keys. The Python workaround
does not... see examples... notice the key(s) that are '4'

Python output (using the k = [] idea):

Key: 4 Value: [[13, 'Visa'], [16, 'Visa']]

A C++ multimap

Key: 4 Value: Visa 16
Key: 4 Value: Visa 13
You are looking at a two-line workaround. A single Key-4 element is
always k[4][0], if 4 is in k. To remove k[4] is a little trickier.
If len( k[4] )1: k[4].pop( ), else k.pop( 4 )[ 0 ]. (Smooth.)
Aug 27 '08 #10
On Aug 27, 1:52*pm, brad <byte8b...@gmail.comwrote:
Mike Kent wrote:
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>k = {}
k['1'] = []
k['1'].append('Tom')
k['1'].append('Bob')
k['1'].append('Joe')
>>k['1']
['Tom', 'Bob', 'Joe']

There is only one '1' key in your example. I need multiple keys that are
all '1'. I thought Python would have something built-in to handle this
sort of thing.

I need a true multimap:

k['1'] = 'Tom'
k['1'] = 'Tommy'

without Tommy overwriting Tom and without making K's value a list of
stuff to append to. That's still just a regular map.
What would you want to happen if you were to execute "print k['1']"?
Best I can tell, you want some sort of association list like this:

k = []
k.append(("1","Tom"))
k.append(("1","Tommy"))

which you can iterate through like this:

for key,value in k:
....

And if you need to retrieve items with a certain "key", probably it's
easiest to maintain sorted invariant, and to do insertion and lookup
with bisection algorithm (see bisect module).

I don't know of any class in the standard library that does all that
for you though.
Out of curiosity, what does a true multimap solve that a dictionary of
lists not solve?
Carl Banks
Aug 28 '08 #11
Carl Banks wrote:
Out of curiosity, what does a true multimap solve that a dictionary of
lists not solve?
Nothing really. I went with a variation of the suggested work around...
it's just that with Python I don't normally have to use work arounds and
normally one obvious approach is correct:

Aug 28 '08 #12
On Aug 28, 2:41*pm, brad <byte8b...@gmail.comwrote:
Carl Banks wrote:
Out of curiosity, what does a true multimap solve that a dictionary of
lists not solve?

Nothing really. I went with a variation of the suggested work around...
it's just that with Python I don't normally have to use work arounds and
* normally one obvious approach is correct:
Might I suggest that the C++ multimap is the workaround, rather than
the Python way of using dicts or lists or dicts of sets?

It was too much programming overhead and line noise confusion to
define nested templates to hold your nested data structures in C++, so
the STL provided a container that eliminated the nesting. In Python,
the obvious nested way to do it is easy, especially now with
defaultdicts, so there was no reason to provide a multimap.
Carl Banks
Aug 28 '08 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Tanguy Fautré | last post by:
Hello, does std::multimap make any guarantee about the insertion order? for example: int main() { std::multimap<int, int> Map;
9
by: Dennis Jones | last post by:
Hi, Is there a way to iterate through a multimap in such a way as to encounter only the unique keys? In other words, since a multimap allows duplicate keys, I would like to iterate through the...
3
by: He Shiming | last post by:
Hi Folks, Happy holidays! I have a question regarding STL multimap. Basically, the current multimap<int,int> look like this: key=>value 1=>10, 1=>20, 1=>30,
4
by: Nick Keighley | last post by:
Hi, I've checked out various documentation for multimap but can't find anywhere it explicitly stated that insert() invalidates multimap iterators. consider this pseudo code:- int...
14
by: Dan Stromberg | last post by:
I've been putting a little bit of time into a file indexing engine in python, which you can find here: http://dcs.nac.uci.edu/~strombrg/pyindex.html It'll do 40,000 mail messages of varying...
4
by: sks | last post by:
I have a question regarding std::multimap/iterators. At the SGI website, it says "Erasing an element from a multimap also does not invalidate any iterators, except, of course, for iterators that...
1
by: Saile | last post by:
I want to give an array the values from the specific multimap's key's values. multimap<string,int> mymultimap; multimap<string,int>::iterator it;...
1
by: ambarish.mitra | last post by:
Hi all, I have a multimap, where key is an int and the value is a class. I can insert into the multimap, but finding it difficult to retrieve the value when keys match. I can do this with...
20
by: puzzlecracker | last post by:
I am using while loop for that but I am sure you can do it quicker and more syntactically clear with copy function. Here is what I do and would like to if someone has a cleaner solution: ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.