473,666 Members | 2,634 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

expression form of one-to-many dict?

So I end up writing code like this a fair bit:

map = {}
for key, value in sequence:
map.setdefault( key, []).append(value)

This code basically constructs a one-to-many mapping -- each value that
a key occurs with is stored in the list for that key.

This code's fine, and seems pretty simple, but thanks to generator
expressions, I'm getting kinda spoiled. ;) I like being able to do
something like the following for one-to-one mappings:

dict(sequence)

or a more likely scenario for me:

dict((get_key(i tem), get_value(item) for item in sequence)

The point here is that there's a simple sequence or GE that I can throw
to the dict constructor that spits out a dict with my one-to-one mapping.

Is there a similar expression form that would spit out my one-to-many
mapping?

Steve
Jul 18 '05 #1
25 2383
[Steven Bethard]
So I end up writing code like this a fair bit:

map = {}
for key, value in sequence:
map.setdefault( key, []).append(value)

This code basically constructs a one-to-many mapping -- each
value that a key occurs with is stored in the list for that key.

This code's fine, and seems pretty simple, but thanks to generator
expressions, I'm getting kinda spoiled. ;) I like being able to do
something like the following for one-to-one mappings:

dict(sequence)

or a more likely scenario for me:

dict((get_key(i tem), get_value(item) for item in sequence)

The point here is that there's a simple sequence or GE that I can
throw to the dict constructor that spits out a dict with my one-to-
one mapping.
It's a simple sequence because it's a simple task. It's even simpler
than perhaps it "should be", since it arbitrarily decides that, if
more than one instance of some key is seen, it will only remember the
value associated with the last instance of that key.
Is there a similar expression form that would spit out my one-to-
manymapping?


There's a straightforward one-liner in 2.4 (but not notably concise),
if your keys are totally ordered:

from itertools import groupby
d = dict((k, map(get_value, g))
for k, g in groupby(sorted( sequence, key=get_key),
key=get_key))

The real purpose of that is to increase your appreciation for your
original spelling <0.2 wink>.
Jul 18 '05 #2
Tim Peters wrote:
The point here is that there's a simple sequence or GE that I can
throw to the dict constructor that spits out a dict with my one-to-
one mapping.

It's a simple sequence because it's a simple task. It's even simpler
than perhaps it "should be", since it arbitrarily decides that, if
more than one instance of some key is seen, it will only remember the
value associated with the last instance of that key.


Good point. That's sort of an arbitrary behavior decision, which, while
reasonable in most situations is not desirable in mine. In thinking
about this, it struck me that one solution is to change that behavior:
class OneToMany(objec t, UserDict.DictMi xin): .... def __init__(*args, **kwds):
.... self, args = args[0], args[1:]
.... self._dict = {}
.... self.update(*ar gs, **kwds)
.... def __getitem__(sel f, key):
.... if not key in self._dict:
.... self._dict[key] = []
.... return self._dict[key]
.... def __setitem__(sel f, key, value):
.... self[key].append(value)
.... def keys(self):
.... return self._dict.keys ()
.... d = OneToMany((pow( i, 13, 4), i) for i in range(10))
d[0] [0, 2, 4, 6, 8] d[1] [1, 5, 9] d[3]

[3, 7]

I'll have to think about whether it would be worth keeping a class like
this around... It might make working with this kind of data
interactively simpler...

Thanks for the comments!

Steve
Jul 18 '05 #3
Steven,

Suggestion: It is a bad idea to name any variable
"map". When you do, you destroy your ability to call
Python's map function. Same goes for "list", "str",
or any other built-in function.

If you haven't been bitten by this you will, I was.

Larry Bates

Steven Bethard wrote:
So I end up writing code like this a fair bit:

map = {}
for key, value in sequence:
map.setdefault( key, []).append(value)

This code basically constructs a one-to-many mapping -- each value that
a key occurs with is stored in the list for that key.

This code's fine, and seems pretty simple, but thanks to generator
expressions, I'm getting kinda spoiled. ;) I like being able to do
something like the following for one-to-one mappings:

dict(sequence)

or a more likely scenario for me:

dict((get_key(i tem), get_value(item) for item in sequence)

The point here is that there's a simple sequence or GE that I can throw
to the dict constructor that spits out a dict with my one-to-one mapping.

Is there a similar expression form that would spit out my one-to-many
mapping?

Steve

Jul 18 '05 #4
Larry Bates wrote:
Suggestion: It is a bad idea to name any variable
"map". When you do, you destroy your ability to call
Python's map function. Same goes for "list", "str",
or any other built-in function.

If you haven't been bitten by this you will, I was.


A good reminder for all the newbies out there.

Sorry, I renamed my variables to simplify the example -- my names
usually look like '<key>_<value>_ map' where <key> and <value> describe
the items in the dict. Since the generic example didn't really have a
description for the keys or values, I stripped it down to map. Fine for
the example, but I should have realized it would draw this comment
(mainly because I probably would have posted a similar one myself if I
had seen the example). ;)

Fortunately, after 2+ years with Python, the risk of me being "bitten"
again by this is pretty small. ;)

Actually, it's even smaller now, because I've pretty much removed map
from all my code in favor of list comprehensions, which I find much
easier to read.

Steve
Jul 18 '05 #5
Steven Bethard wrote:
Actually, it's even smaller now, because I've pretty much removed map
from all my code in favor of list comprehensions, which I find much
easier to read.


While I agree that listcomps are more readable in most cases (and certainly for
all cases with any amount of complexity in the listcomp), I still find that
map is hard to beat for the simple case of a callable foo:

outlist = map(foo,inlist)

is still better in my book, and far more readable, than

outlist = [foo(x) for x in inlist]

The map form, in this case, parses instantly in my brain, while the listcomp
certainly takes a few cycles. And note that I'm not talking about the typing
conciseness, but about the effort for my brain. But maybe I'm just wired
funny :)

Since I tend to have a lot of code like this, I really cringe when I hear of a
desire to do away with map altogether. I know I could rewrite it myself in
all my code, but the beauty of these builtins is that they are always there...

Cheers,

f

Jul 18 '05 #6
Fernando Perez wrote:

outlist = map(foo,inlist)

is still better in my book, and far more readable, than

outlist = [foo(x) for x in inlist]

The map form, in this case, parses instantly in my brain, while the listcomp
certainly takes a few cycles. And note that I'm not talking about the typing
conciseness, but about the effort for my brain. But maybe I'm just wired
funny :)


Well, different at least. I find the map one harder to parse mentally.
And not for lack of experience with functional programming. But to
each their own. =)

Steve
Jul 18 '05 #7
Steven Bethard wrote:
The map form, in this case, parses instantly in my brain, while the listcomp
certainly takes a few cycles. And note that I'm not talking about the typing
conciseness, but about the effort for my brain. But maybe I'm just wired
funny :)


Well, different at least. I find the map one harder to parse mentally.


if you have trouble parsing a function call, I'm glad I don't have to maintain
your Python programs...

</F>

Jul 18 '05 #8
Fredrik Lundh wrote:
Steven Bethard wrote:
The map form, in this case, parses instantly in my brain, while the listcomp
certainly takes a few cycles. And note that I'm not talking about the typing
concisenes s, but about the effort for my brain. But maybe I'm just wired
funny :)


Well, different at least. I find the map one harder to parse mentally.


if you have trouble parsing a function call, I'm glad I don't have to maintain
your Python programs...


I don't know what I said to upset you so, but I do apologize.

If you could tell me what it was about my statement (that I find a list
comprehension to be a clearer description of program flow than a map
application[1]) that so insulted you, I would be glad to avoid such
comments in the future, if it would avoid such vicious replies from you.

Steve

[1] In my mind, the program flow is spelled out explicitly in the list
comprehension and only implicitly in the map application. Thus the list
comprehension is clearer to me.
Jul 18 '05 #9
In respect to map(func, seq) versus [func(i) for i in seq], for
pre-existing func, 'OP' wrote
The map form, in this case, parses instantly in my brain, while the
listcomp
certainly takes a few cycles. And note that I'm not talking about the
typing
conciseness , but about the effort for my brain. But maybe I'm just
wired
funny :)
Steven Bethard wrote:
Well, different at least. I find the map one harder to parse mentally.
[and] [1] In my mind, the program flow is spelled out explicitly in the list
comprehension and only implicitly in the map application. Thus the list
comprehension is clearer to me.


For pre-existing func, I slightly prefer the map form because the
sequential program flow is *not* spelled out. So I can more easily see the
sequence items mapped in parallel. On the other hand, I probably prefer
[i-expression for i in seq] to map(lambda i: i-expression, seq) because I
find the (unnecessary) mental construction of a function object to be a
compensating burden.

I can easily imagine that others will find themselves more comfortably on
one side or the other of the mental fence I find myself sitting on ;-).

Terry J. Reedy

Jul 18 '05 #10

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

Similar topics

0
3081
by: alexz | last post by:
valuA = (request.form("toadd")) If valuA = "" then SQL = "UPDATE CourseReg SET attended='Active' WHERE ID IN("&request.form("toadd")&")" Set RS = MyConn.Execute(SQL) End If MyConn.Close Set RS = Nothing Set MyConn = Nothing
5
6563
by: Dave Miller | last post by:
Hello - I have a form field the results from which should not start with a digit. I have tried various permutations of the following without success. Can anyone help me out? //does not return false when it should (document.my_form.my_field.value.substring(0) == / \d /) TIA
2
6163
by: Aloof | last post by:
Using Access 2000 Windows Server 2003 The following code worked fine until we moved hosting companies StartDate = Request.Form("StartDateMonth") & "/" & Request.Form ("StartDateDay") & "/" & Request.Form("StartDateYear") EndDate = Request.Form("EndDateMonth") & "/" & Request.Form ("EndDateDay") & "/" & Request.Form("EndDateYear")
1
3718
by: Gil | last post by:
This is a question involving CORBA but the problem shows up using Sun C++. The problem doesn't occur with Visual C++ 6. I'm using a string in the following form in my CORBA IDL declaration so both the client and server will have common strings defined. module A { interface B { const string MY_STRING = "thestring"; }
6
4537
by: Joe Abou Jaoude | last post by:
hi, I need to verify that the user enter only one word in a textbox. So i thought to add a regularexpression validator and disallow the user to enter a space between the letters he wrote. how can i do that ? thx *** Sent via Developersdex http://www.developersdex.com ***
1
3800
by: Grant Hammond | last post by:
I assume I'm not alone in my frustration that the expression builder that comes (in part) with Access XP that dosnt wrap text when you open it on an exisitng expression in a query or form. I's bad enough that Microsoft dropped the expression builder from the VB window (which I have restored using Michael Kaplan addin), but I cant understand how they could not have fixed this obviously and annoying BUG!@
3
1442
by: Henrootje | last post by:
Hello folks, I have a groupBy query, in one of the columns (SNISNU_KWARTAAL) there is a textfield. I have an expression that deducts (from a numeric field) another expression that has the same shape as the values in SNISNU_KWARTAAL. I want that expression used as the criterium on the textfield but it then gives me no results! I made a new column (Kwartaal) with the expression that shows the computed value.
2
2156
by: parul.prasad | last post by:
How can we evaluate a string expression in if statement Linux C/C++
1
17518
by: Zorik | last post by:
I am building a form in asp.net 2.0 On one of the textboxes, I don't want that the user will use the space character. How do I disallow space using regular expression validator (or other validator) ? Thanks ra294
2
340
by: pintu | last post by:
Hi I am writing a validation expression for the followings 1)EPF/chp15_v3.htm#p33 or 2)EPF/chp15_v3.htm I wrote the validation expression as *\.(htm|html)\#*$
0
8440
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
8863
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8780
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...
1
8549
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6189
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
5661
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
4192
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
4358
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.