473,788 Members | 2,733 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dictionary initialization

Hi,

With awk, I can do something like
$ echo 'hello' |awk '{a[$1]++}END{for(i in a)print i, a[i]}'

That is, a['hello'] was not there but allocated and initialized to
zero upon reference.

With Python, I got
b={}
b[1] = b[1] +1

Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 1

That is, I have to initialize b[1] explicitly in the first place.

Personally, I think

a[i]++

in awk is much more elegant than

if i in a: a[i] += 1
else: a[i] = 1

I wonder how the latter is justified in Python.

Thanks,
Weiguang
Jul 18 '05
26 2862

"Dan Perl" <da*****@rogers .com> wrote in message
news:uf******** ************@ro gers.com...

"Caleb Hattingh" <ca****@telkoms a.net> wrote in message
news:op******** ******@news.tel komsa.net...
IF this is the point you are making, and the awk functionality
demostrated in this particular example is a really significant feature
for you in your specific problem domain, then I must concede that awk is
probably right for you, and you shouldn't waste your time with Python.


And just like that, the discussion turned religious. It's hard to assess
someone's tone when it comes in writing, but, Caleb, you sound sarcastic
and belligerent to me.


To me, Caleb was being only slightly and possibly sarcastic in the process
of giving friendly good advice to the effect of "better to use Awk and
produce than to beat you head against a wall trying to change a basic
Python design decision.

Almost every design decision has plusses and minuses for designers and
others to weigh. No matter what the designer decides, there will be users
who weigh the factors enough differently to really wish that the decision
was otherwise. In fact, there will probably be another language whose
designer did decide otherwise. And in this case, with regard to the
handling of uninitialized variables, there is.

A Python religion fanatic might have made the opposite suggestion --
something like 'your factor weighting is wrong; see the light and bow to
the superior wisdom of how Python does it'.

Terry J. Reedy

Jul 18 '05 #21
Weiguang Shi wrote:
Personally, I think

a[i]++

in awk is much more elegant than

if i in a: a[i] += 1
else: a[i] = 1


As others have pointed out, the type of an uninitialized a[i] is
ambiguous, and that Python doesn't want to try to guess what type to use
based only on the type of the RHS. Depending on what, exactly, the RHS
*is*, there may be multiple likely types for the LHS. The case where
the RHS is an integer is one of the clearer special cases, but Python's
default behavior should be the same regardless of what type the RHS is,
and it doesn't seem safe to assume that the LHS type should always be
equivalent to the RHS type.

But there's another level of ambiguity here. In many cases, throwing an
error for an uninitialized dict item *is* the correct behavior. Suppose
I've got an ascii string representing a DNA gene sequence, and I want to
calculate the relative prevalence of various bases. It's pretty
straightforward to go through and count up how many of each character
there are, using a dict -- but if somehow a letter other than A, G, C,
or T is present, I don't want it to pass silently. It's something very
strange/wrong, and I want to be notified immediately.

Now, in the counting that *you* happen to be doing, assuming that a
default value is desirable works. But that's not universal. And it's
easier to use one of various methods to create a default value (as Bengt
Richter demonstrated) than it is to consistently check that the dict
keys are limited to a particular set of desired keys.

Also, it's not that hard to subclass dict to provide the functionality
that you want. I expect that googling on the c.l.p archives would turn
up more than one recipe for a dict with default values. (There may even
be such a thing in the Python Cookbook.) I know I've seen such things
posted here (though not recently).

Jeff Shannon
Technician/Programmer
Credit International
Jul 18 '05 #22
Jeff Shannon <je**@ccvcorp.c om> wrote:
Also, it's not that hard to subclass dict to provide the functionality
that you want. I expect that googling on the c.l.p archives would turn
up more than one recipe for a dict with default values. (There may even
be such a thing in the Python Cookbook.) I know I've seen such things
posted here (though not recently)


There are several such recipes. The most promising IMHO is Hettinger's
'bag' class (doesn't subclass dict -- uses containment and delegation --
but it deals best with maintaining count-per-item, aka multiset or bag);
it has several bugs as posted, but I've just finished editing it for the
2n edition and it wasn't hard to clear up. I do hope we'll have a
collections.bag in Python 2.5 one day.
Alex
Jul 18 '05 #23
Caleb Hattingh wrote:
IF this is the point you are making, and the awk functionality
demostrated in this particular example is a really significant feature
for you in your specific problem domain, then I must concede that awk
is probably right for you, and you shouldn't waste your time with Python.


Unfortunately for the logic, if one finds something like
that to be a "really significant feature ... [in a] specific problem
domain", then with Python you can of course create your own
custom data type which behaves exactly as desired. And in fact
it is likely that there is additional behaviour that could be
added that would make the Python approach to the problem *even
simpler than the awk approach*, but maybe that's getting too
much of a good thing...

Of course, this capability prevents one from whining about how
wonderful a specialized limited-purpose tool is compared to
that waste of space called Python, but if it weren't for people
like that Usenet would have no traffic and we'd all have lives
instead.

-Peter
Jul 18 '05 #24
Peter,

Right :)

I was trying to kill off (with kindness) a thread that just wasn't making
sense. The other respondents gave pretty good technical explanations
regarding the dynamic typing rules, but I suspect the OP's assertion was
just what I described in the simplest terms I could. Which doesn't make
sense as a critical language feature/flaw.

thx
Caleb

On Sat, 27 Nov 2004 12:59:00 -0500, Peter Hansen <pe***@engcorp. com> wrote:
Caleb Hattingh wrote:
IF this is the point you are making, and the awk functionality
demostrated in this particular example is a really significant feature
for you in your specific problem domain, then I must concede that awk
is probably right for you, and you shouldn't waste your time with
Python.


Unfortunately for the logic, if one finds something like
that to be a "really significant feature ... [in a] specific problem
domain", then with Python you can of course create your own
custom data type which behaves exactly as desired. And in fact
it is likely that there is additional behaviour that could be
added that would make the Python approach to the problem *even
simpler than the awk approach*, but maybe that's getting too
much of a good thing...

Of course, this capability prevents one from whining about how
wonderful a specialized limited-purpose tool is compared to
that waste of space called Python, but if it weren't for people
like that Usenet would have no traffic and we'd all have lives
instead.

-Peter


Jul 18 '05 #25
Hi Dan

I must confess that upon rereading my words, there is some irony there
(but not really sarcasm, is there?). However, I *really* tried to keep
my tone, well, professional. I realise I didn't do a good job and
apologise. I hope that's ok.

Keep well
Caleb

Jul 18 '05 #26
<ca************ @gmail.com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
Hi Dan

I must confess that upon rereading my words, there is some irony there
(but not really sarcasm, is there?). However, I *really* tried to keep
my tone, well, professional. I realise I didn't do a good job and
apologise. I hope that's ok.

Keep well
Caleb


It's water under the bridge. I admire though the fact that you sent this
message.

Dan
Jul 18 '05 #27

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

Similar topics

0
2515
by: jordi | last post by:
Hi, I'm starting to use Python embedded in a C program. I'm using Python to execute several scripts using as a variables information retrieved for several multithread "agents" written in C. The method is: 1- Create a thread for each agent (I use a pool thread, every agent run in a different thread) 2- Precompile a different script for each agent. 3- Make the agent retrieve its data
1
3591
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148 respectively In the sample code you see that I have class Item and class Dict class Dict contains a dictionary called items. The items dictionary will contain instances of Item that are keyed off of the Item name. In __main__ I create two...
1
1674
by: gyro | last post by:
Hi, I have a collection of objects that I am currently trying to manage. Each object is initialized with a dictionary. The dictionaries have the same keys but may have different values. The initialization process is time consuming, so I don't want to create an object if I have already instantiated one using a dictionary with the 'same' items. I would like to collect the objects in a dictionary with the objects as values and some...
8
2489
by: Benjamin Scott | last post by:
Hello. I attempted to build a compound dictionary: len(Lst)=1000 len(nuerLst)=250 len(nuestLst)=500 Dict={}
4
2520
by: brianobush | last post by:
# # My problem is that I want to create a # class, but the variables aren't known # all at once. So, I use a dictionary to # store the values in temporarily. # Then when I have a complete set, I want to # init a class from that dictionary. # However, I don't want to specify the # dictionary gets by hand # since it is error prone.
125
7229
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
1
9263
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex DataBinding accepts as a data source either an IList or an IListSource at System.Windows.Forms.ListControl.set_DataSource(Object value)
8
1531
by: Almad | last post by:
Hello, I discovered this behaviour in dictionary which I find confusing. In SneakyLang, I've tried to extend dictionary so it visits another class after something is added: class RegisterMap(dict): def __setitem__(self, k, v): dict.__setitem__(self, k,v) self.visit_register_map(self)
4
3714
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and value-initialization. I think default-init calls default constructor for class objects and sets garbage values to PODs. Value-init also calls default constructor for class objects and sets 0s to POD types. This is what I've learned from the books (especially...
0
10177
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
10113
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,...
0
9969
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8995
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
7519
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
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4074
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
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2896
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.