Solved

A more concise way to write this?

Posted on 2006-07-19
6
201 Views
Last Modified: 2010-04-16
Is there a more concise way to write this in Python?

cur = aToListB.get(elementA, [])
cur.append(listB)
aToListB[elementA] = cur
   

In Perl, for example, I could express this in one line:

push( @{$aToListB{elementA}}, listB )


Thanks.
0
Comment
Question by:BerkeleyJeff
  • 2
  • 2
  • 2
6 Comments
 
LVL 14

Accepted Solution

by:
RichieHindle earned 500 total points
ID: 17136835
Yes, you can, using the rather oddly-named setdefault() function:

   aToListB.setdefault(elementA, []).append(listB)

setdefault() says "return the value for this key, and if it's not already there, set it to this value first."

Here's a test script:

def Jeff(aToListB, elementA, listB):
    cur = aToListB.get(elementA, [])
    cur.append(listB)
    aToListB[elementA] = cur
    return aToListB

def Richie(aToListB, elementA, listB):
    aToListB.setdefault(elementA, []).append(listB)
    return aToListB

for test in Jeff, Richie:
    print test({}, 'one', 1)           # Empty dict
    print test({'one': []}, 'one', 1)  # dict with empty value
    print test({'one': [1]}, 'one', 2) # dict with existing value


The script prints:

{'one': [1]}
{'one': [1]}
{'one': [1, 2]}
{'one': [1]}
{'one': [1]}
{'one': [1, 2]}

0
 

Author Comment

by:BerkeleyJeff
ID: 17136890
Thanks! That's exactly what I was looking for.

setdefault certainly is an odd name. I think that they should just call it 'set', to make clear its role as the counterpart of 'get'. Or perhaps get should instead be called getdefault.

I'm a bit confused by the return type of setdefault. It must be returning aToListB by reference, rather than by value, since otherwise  'append' wouldn't be mutating aToListB. But I thought arguments to functions were passed by value in Python, rather than being passed by reference.
0
 
LVL 28

Expert Comment

by:pepr
ID: 17137215
The doc says (2.3.8 Mapping Types -- classdict)

   "a.setdefault(k[, x])     ...   a[k] if k in a, else x (also setting it)

    setdefault() is like get(), except that if k is missing, x is both returned and inserted into the dictionary as the value of k. x defaults to None."

In Python, every variable is a named reference, never the value. When name is used as a function argument, the reference is copied and the copy is bound to the internal name inside the function. When assigning the variable, you are always copying the reference that is then bound to the name of the variable. But the name may be later rebound to another reference.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 14

Expert Comment

by:RichieHindle
ID: 17137319
Here's my version of what pepr said:

There is no "pass by reference" or "pass by value" in Python, only "pass by object reference", along with the fact that some objects are mutable and some are not.  So passing the number 3 to a function passes a reference to the number 3.  You can't change the number 3, so in this case Python behaves in a "pass by value" kind of way.  If you pass a list to a function, that can be changed, so Python behaves in a "pass by reference" way.  But really both are the same - in both cases, a reference to an object is being passed.  The only difference is that one object is mutable and the other isn't.

Names in Python are references to objects.  If you say "x = 3" you are defining a named reference to the number 3.  If you then pass x to a function, you are passing a reference to the number 3.  The function doesn't know that the reference was originally called x, and can do nothing to the name x.  If you say "x = [3]", you are defining a named reference to a list which refers to the number 3.  If you pass x to a function, you are passing a reference to that list.  Because lists are mutable, the list can be changed by that function.  The function can't change the fact that x points to that list, but it can change the list itself.

You should read this: http://effbot.org/zone/python-objects.htm  Pay particular attention to the "Introduction" section.  8-)
0
 
LVL 28

Expert Comment

by:pepr
ID: 17137451
... and to add. In fact, names does not matter. Everything important is related to the objects (and their classes). References can exist without a name (for example when stored inside a list). References are the unambiguous identifications plus the built-in behaviour of the interpreter (how the references should be treated). Current CPython implements the identification as the memory address where the objects sits.

A name is always bound to an object. The binding of the name to the object is done via some of the internal dictionaries accessible via built-in functions locals() and globals(). The key is the name, the value is the reference.
0
 

Author Comment

by:BerkeleyJeff
ID: 17164824
I've got a similar question about setdefault, which I posted here:

http://www.experts-exchange.com/Programming/Programming_Languages/Python/Q_21929043.html

I would appreciate any help you can offer.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now