473,788 Members | 2,868 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 2861
Weiguang Shi wrote:
In article <lI************ ********@rogers .com>, Dan Perl wrote:
That would not be justified in python. The type of b[1] is
undetermine d until initialization and I don't see why it should be
an int by default.


In my example, it was b[1]+=1. "+=1" should at least tell Python two
things: this is an add operation and one of the operands is an
integer.


Why would it tell Python that?
b = {1: 2.5}
b[1] += 1
b

{1: 3.5}

So at this point, it can clearly be either an integer or
a float. Doubtless it could also be an object which
overloads the += operator with integer arguments, though
what it might actually do is anyone's guess.

-Peter
Jul 18 '05 #11
wg***@namao.cs. ualberta.ca (Weiguang Shi) writes:
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.


It isn't :-)
a={}
a[1] = a.get(1, 0) + 1
a {1: 1} a[1] = a.get(1, 0) + 1
a

{1: 2}

Regards
Berthold
--
be******@xn--hllmanns-n4a.de / <http://höllmanns.de/>
bh***@web.de / <http://starship.python .net/crew/bhoel/>
Jul 18 '05 #12

wg***@namao.cs. ualberta.ca (Weiguang Shi) wrote:

In article <lI************ ********@rogers .com>, Dan Perl wrote:
I don't know awk, so I don't know how your awk statement works.

It doesn't hurt to give it a try :-)

Even when it comes to the python statements, I'm not sure exactly what the
...

I see your point.

You're saying that in awk a['hello'] is initialized to 0.

More than that; I said awk recognizes a['hello']++ as an
arithmetic operation and initializes a['hello'] to 0 and add one to
it. (This is all guess. I didn't implement gawk. But you see my point.)
That would not be justified in python. The type of b[1] is
undetermined until initialization and I don't see why it should be
an int by default.

In my example, it was b[1]+=1. "+=1" should at least tell Python two
things: this is an add operation and one of the operands is an
integer. Based on these, shouldn't Python be able to insert the pair
"1:0" into a{} before doing the increment?


As Peter has already mentioned, since b[1] doesn't exist until you
assign it, the type of b[1] is ambiguous.

The reason Python doesn't do automatic assignments on unknown access is
due to a few Python 'Zens'
import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Specifically:
Explicit is better than implicit.
(you should assign what you want, not expect Python to know what you
want)
Special cases aren't special enough to break the rules.
(incrementing non-existant values in a dictionary shouldn't be any
different from accessing non-existant values)
In the face of ambiguity, refuse the temptation to guess.
(what class/value should the non-existant value initialize to?)
Learn the zens. Any time you have a design question about the Python,
check the zens, then check google, then check here.

- Josiah

Jul 18 '05 #13
I see.

Thanks
Weiguang
Jul 18 '05 #14
Weiguang Shi wrote:
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 ... <snip>
I have to initialize b[1] explicitly in the first place.


You could use the dictionary's setdefault method, if your value is mutable:
b={}
for n in xrange(100): .... b.setdefault('f oo', [0])[0] += 1
.... b['foo'][0]

100

Jeffrey
Jul 18 '05 #15
Peter Hansen wrote:
In my example, it was b[1]+=1. "+=1" should at least tell Python two
things: this is an add operation and one of the operands is an
integer.


Why would it tell Python that?


Well, the rhs of 'foo+=1' is always an integer.

Gerrit.

--
Weather in Lulea / Kallax, Sweden 26/11 17:20:
-8.0°C wind 6.7 m/s NW (34 m above NAP)
--
In the councils of government, we must guard against the acquisition of
unwarranted influence, whether sought or unsought, by the
military-industrial complex. The potential for the disastrous rise of
misplaced power exists and will persist.
-Dwight David Eisenhower, January 17, 1961
Jul 18 '05 #16
Just received an email from Batista, Facundo. Below are some quote and
my reply.

On Fri, Nov 26, 2004 at 09:09:46AM -0300, Batista, Facundo wrote:
...
>>> a = {}
>>> a['1'] = 5
>>> a['1'] *= 2
>>> a['1'] 10
>>> a['1'] = "blah"
>>> a['1'] *= 2
>>> a['1'] 'blahblah'
>>> a['1'] = ['a', 8]
>>> a['1'] *= 2
>>> a['1']

['a', 8, 'a', 8]

The type of the right hand operator does not have nothing to do with
the
type of the left operand!


You mean in Python, of course. I can see this is going the religious
direction now.

All in all, I've realized when a language generalizes and abstracts,
it loses convenience. Because of this, however powerful other
languages become, awk always has its place as long as the application
is there.

Weiguang
Jul 18 '05 #17
Hi Weiguang

I know how it is when discussion becomes religious, and I want to avoid
that. First, I want to clarify exactly what it is that you are saying:

Would I be correct in saying that your point is that with awk, you can
just do something like (ignore the syntax)

(x not existing yet)
x+=1

And have x = 1, while in Python you have to do

(x not existing yet)
x=0
x+=1

And then have x=1? Is this the question of debate here? One line of
initialisation to specify the type?

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.

Keep well
Caleb
On Fri, 26 Nov 2004 17:53:12 +0000 (UTC), Weiguang Shi
<wg***@namao.cs .ualberta.ca> wrote:

You mean in Python, of course. I can see this is going the religious
direction now.

All in all, I've realized when a language generalizes and abstracts,
it loses convenience. Because of this, however powerful other
languages become, awk always has its place as long as the application
is there.

Weiguang


Jul 18 '05 #18
Caleb,

In article <op************ **@news.telkoms a.net>, Caleb Hattingh wrote:
...
And then have x=1? Is this the question of debate here? One line of
initialisati on to specify the type? Right.

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.

Thanks for the advice. I'll stay with awk and shell for most of my
text processing (simple but, hey, 90% of the time I'm not doing
anything complex) and go Python for binary data processing and larger
projects. BTW, I think learning Python is a good use of my time.

Weiguang
Jul 18 '05 #19

"Caleb Hattingh" <ca****@telkoms a.net> wrote in message
news:op******** ******@news.tel komsa.net...
Hi Weiguang

I know how it is when discussion becomes religious, and I want to avoid
that. First, I want to clarify exactly what it is that you are saying:

Would I be correct in saying that your point is that with awk, you can
just do something like (ignore the syntax)

(x not existing yet)
x+=1

And have x = 1, while in Python you have to do

(x not existing yet)
x=0
x+=1

And then have x=1? Is this the question of debate here? One line of
initialisation to specify the type?

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.

Yes, 2 lines instead of 1 is an issue. And it is not the only example where
the "explicit is better than implicit" principle shows a downside. However,
addressing Weiguang's statements, I wouldn't say that python is less
convenient than other languages (particularly awk, although I don't know
that language), because I am sure we can find examples where python can
implement something in a simpler way.

Dan
Keep well
Caleb

Jul 18 '05 #20

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
9656
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
9498
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
10366
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...
1
10112
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
8993
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...
0
6750
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
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4070
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
3
2894
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.