473,699 Members | 2,628 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 7440
On Aug 27, 9:35*am, brad <byte8b...@gmai l.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(lis t)
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__(sel f, 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__(sel f, 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...@gmai l.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_Expres s 15
Key: 35 Value: JCB 16
Key: 36 Value: Diners_Club 14
Key: 37 Value: American_Expres s 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...@gmai l.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

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

Similar topics

12
13452
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
7861
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 entire multimap, and if a particular key has duplicates, only see one of them. I don't think I care about which of the duplicate entries I see, because once I have an entry, I can use lower_bound and upper_bound to iterate through them, right? ...
3
6296
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
4499
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 DataItem::genDerived () {
14
1805
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 lengths pretty well now, but I want more :) So far, I've been taking the approach of using a single-table database like gdbm or dbhash (actually a small number of them, to map filenames to numbers, numbers to filenames, words to numbers, numbers to...
4
4229
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 actually point to the element that is being erased." I design/implemented a observer pattern that is priority based. It so happened that observers were deregistering themselves while they were being notified. In other words, we were iterating...
1
2712
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; pair<multimap<string,int>::iterator,multimap<string,int>::iterator> ret; mymultimap.insert (pair<string,int>("test",10)); mymultimap.insert (pair<string,int>("test",20)); mymultimap.insert (pair<string,int>("ab",100)); mymultimap.insert (pair<string,int>("ab",200));
1
2228
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 primitive types (int/char etc). Example: class A {
20
3985
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: vector<stringvec; multimap<stirng, intmyMap // populate myMap
0
8687
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8617
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9035
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7751
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6534
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5875
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4376
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2347
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.