473,553 Members | 2,957 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to say $a=$b->{"A"} ||={} in Python?

Hi All.

I'd like to do the following in more succint code:

if k in b:
a=b[k]
else:
a={}
b[k]=a

a['A']=1
In perl it is just one line: $a=$b->{"A"} ||={}.

Thanks,
Geoffrey

Aug 16 '07 #1
18 1796
beginner <zy*******@gmai l.comwrote:
I'd like to do the following in more succint code:

if k in b:
a=b[k]
else:
a={}
b[k]=a
b.setdefault(k, a)

--
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand
something when his salary depends on not
understanding it" - Upton Sinclair
Aug 16 '07 #2
On Aug 16, 5:43 pm, ra...@dot.com (Lawrence Oluyede) wrote:
beginner <zyzhu2...@gmai l.comwrote:
I'd like to do the following in more succint code:
if k in b:
a=b[k]
else:
a={}
b[k]=a

b.setdefault(k, a)

--
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand
something when his salary depends on not
understanding it" - Upton Sinclair
I am afraid it is not the same. b.setdefault(k, {}) will always create
an empty dict, even if k is in b, as demonstrated in the below code.

b={}
def f(i):
print "I am evaluated %d" % i
return i

b.setdefault('A ', f(1))
b.setdefault('A ', f(2))
b
Aug 16 '07 #3
On Aug 16, 6:35 pm, beginner <zyzhu2...@gmai l.comwrote:
Hi All.

I'd like to do the following in more succint code:

if k in b:
a=b[k]
else:
a={}
b[k]=a

a['A']=1

In perl it is just one line: $a=$b->{"A"} ||={}.

Thanks,
Geoffrey
Define b as a default dict:

b = defaultdict(dic t)
b[k]['A'] = l

Carl Banks

Aug 16 '07 #4
On Aug 16, 3:35 pm, beginner <zyzhu2...@gmai l.comwrote:
>
In perl it is just one line: $a=$b->{"A"} ||={}.
a = b.setdefault('A ', {})

This combines all two actions together:
- Sets b['A'] to {} if it is not already defined
- Assigns b['A'] to a

More info on dict methods here:

http://docs.python.org/lib/typesmapping.html

Aug 17 '07 #5
On Aug 16, 8:28 pm, Jonathan Gardner
<jgardner.jonat hangardner....@ gmail.comwrote:
On Aug 16, 3:35 pm, beginner <zyzhu2...@gmai l.comwrote:
In perl it is just one line: $a=$b->{"A"} ||={}.

a = b.setdefault('A ', {})

This combines all two actions together:
- Sets b['A'] to {} if it is not already defined
- Assigns b['A'] to a

More info on dict methods here:

http://docs.python.org/lib/typesmapping.html
No, this has already been proposed and discarded. The OP does NOT
want this, because it always generates an empty {} whether it is
needed or not. Not really a big hardship, but if the default value
were some expensive-to-construct container class, then you would be
creating one every time you wanted to reference a value, on the chance
that the key did not exist.

Carl Banks' post using defaultdict is the correct solution. The
raison d'etre for defaultdict, and the reason that it is the solution
to the OP's question, is that instead of creating a just-in-case
default value every time, the defaultdict itself is constructed with a
factory method of some kind (in practice, it appears that this factory
method is usually the list or dict class constructor). If a reference
to the defaultdict gives a not-yet-existing key, then the factory
method is called to construct the new value, that value is stored in
the dict with the given key, and the value is passed back to the
caller. No instances are created unless they are truly required for
initializing an entry for a never-before-seen key.

-- Paul

Aug 17 '07 #6
On Aug 16, 6:03 pm, Carl Banks <pavlovevide... @gmail.comwrote :
On Aug 16, 6:35 pm, beginner <zyzhu2...@gmai l.comwrote:
Hi All.
I'd like to do the following in more succint code:
if k in b:
a=b[k]
else:
a={}
b[k]=a
a['A']=1
In perl it is just one line: $a=$b->{"A"} ||={}.
Thanks,
Geoffrey

Define b as a default dict:

b = defaultdict(dic t)
b[k]['A'] = l

Carl Banks- Hide quoted text -

- Show quoted text -
I think the most direct translation of the OP's example to Python
would be:

# setup b as special flavor of dict, that creates a
# new dict for not-yet-created keys
b = defaultdict(dic t)

# actual python impl of $a=$b->{k}||={}
a = b[k]

# assign 1 to retrieved/created dict
a['A'] = 1

-- Paul

Aug 17 '07 #7
On Fri, 2007-08-17 at 00:53 +0000, beginner wrote:
$b is supposed to be a hash-table of hash-table. If a key exists in
$b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is
useful when you want to add records to the double hash table.

For example, if you have a series of records in the format of (K1, K2,
V), and you want to add them to the double hash-table, you can do
$a=$b->{K1} || ={}
$a->{K2}=V
What is the best solution in Perl need not be the best solution in
Python. In Python you should just use a tuple as your dict key, i.e.
a[k1,k2] = v, unless you have some other constraints you're not telling
us.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
Aug 17 '07 #8
On Aug 16, 9:32 pm, Carsten Haese <cars...@uniqsy s.comwrote:
On Fri, 2007-08-17 at 00:53 +0000, beginner wrote:
$b is supposed to be a hash-table of hash-table. If a key exists in
$b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is
useful when you want to add records to the double hash table.
For example, if you have a series of records in the format of (K1, K2,
V), and you want to add them to the double hash-table, you can do
$a=$b->{K1} || ={}
$a->{K2}=V

What is the best solution in Perl need not be the best solution in
Python. In Python you should just use a tuple as your dict key, i.e.
a[k1,k2] = v, unless you have some other constraints you're not telling
us.

HTH,

--
Carsten Haesehttp://informixdb.sour ceforge.net
I use tuples this way all the time. It is indeed very neat. But it is
not a replacement for double hash-table. If I want to retrieve
information just by K1, it is not efficient to index on (K1, K2).

Aug 17 '07 #9
On Aug 16, 5:35 pm, beginner <zyzhu2...@gmai l.comwrote:
Hi All.

I'd like to do the following in more succint code:

if k in b:
a=b[k]
else:
a={}
b[k]=a

a['A']=1

In perl it is just one line: $a=$b->{"A"} ||={}.

Thanks,
Geoffrey
It looks like defaultdict is the solution for this kind of thing.
Thanks all for your help.

Aug 17 '07 #10

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

Similar topics

4
3405
by: Askari | last post by:
Yesterday, ALL code in python work and nothing when I close(finish) a code. Today, when I close, some raise this windows error : Instruction at "0x00FC3D70" use memory address "0x00000000". Can't be "read". Click on "OK" to exit program. Why this error, today and not before today?
40
3000
by: Steve Juranich | last post by:
I know that this topic has the potential for blowing up in my face, but I can't help asking. I've been using Python since 1.5.1, so I'm not what you'd call a "n00b". I dutifully evangelize on the goodness of Python whenever I talk with fellow developers, but I always hit a snag when it comes to discussing the finer points of the execution...
9
1609
by: Lonnie Princehouse | last post by:
There doesn't seem to be any way to customize the behavior of "is" as can be done for other operators... why not?
28
2965
by: john_sips_tea | last post by:
Just tried Ruby over the past two days. I won't bore you with the reasons I didn't like it, however one thing really struck me about it that I think we (the Python community) can learn from. Ruby has ... an issue with docs. That is to say, there are almost none. Well, actually, there are some. For example, the "PickAxe" book (google it),...
6
12388
by: openopt | last post by:
Thank you in advance for your response. Dmitrey
25
2553
by: samjnaa | last post by:
Please check for sanity and approve for posting at python-dev. In Visual Basic there is the keyword "with" which allows an object- name to be declared as governing the following statements. For example: with quitCommandButton .enabled = true .default = true end with
92
3873
by: ureuffyrtu955 | last post by:
Python is a good programming language, but "Python" is not a good name. First, python also means snake, Monty Python. If we search "python" in google, emule, many results are not programming resource. If we search PHP, all results are programming resource. Second, python also means snake, snake is not a good thing in western culture....
6
1753
by: grbgooglefan | last post by:
I am creating functions, the return result of which I am using to make decisions in combined expressions. In some expressions, I would like to inverse the return result of function. E.g. function contains(source,search) will return true if "search" string is found in source string. I want to make reverse of this by putting it as: if ( !...
10
1577
by: Prisoner at War | last post by:
Hi, your friendly neighborhood n00b here, just wondering why on earth the Py3K folks want to mess with a simple thing like the "print" "command" (is that what it's called, a command?), turning it into "print()"...I mean, what's the point, exactly?? To look like a more "traditional" computer-language format? And what's with not supporting...
1
2005
by: =?ISO-8859-1?Q?Andr=E9?= | last post by:
Hi everyone, I'd be interested in hearing suggestions as to the "best" way to drive a Python program step by step from another application. Details: --------- I have implemented a "Robot" that can be programmed by a user to perform certain actions. (see Reeborg below for a simple javascript-
0
7568
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...
0
7492
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...
0
8007
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...
0
6109
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...
0
5133
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...
0
3525
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1990
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1106
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
808
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...

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.