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 26 2860
Hmm :)
"b[1]" looks like a List (but you created a Dict)
"b['1'] looks more like a Dict (but this is not what you used).
If lists are your thing: a = [] a.append(1) a
[1] a[0] += 1 a
[2]
If dicts are your thing:
b = {} b['1'] = 1 b
{'1': 1} b['1'] += 1 b
{'1': 2}
Lists are ordered, Dicts are not.
Dict entries accessed with 'string' keys, List entries accessed with a
position integer.
Which feature specifically do you want justification for?
thx
Caleb 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
On Thu, 25 Nov 2004 18:38:17 +0000 (UTC), wg***@namao.cs. ualberta.ca (Weiguang Shi) wrote: 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.
You wrote it, so you have to "justify" it ;-)
While I agree that ++ and -- are handy abbreviations, and creating a key by default
makes for concise notation, a[i]++ means you have to make some narrow assumptions -- i.e.,
that you want to create a zero integer start value. You can certainly make a dict subclass
that behaves that way if you want it: class D(dict):
... def __getitem__(sel f, i):
... if i not in self: self[i] = 0
... return dict.__getitem_ _(self, i)
... dink = D() dink
{} dink['a'] +=1 dink
{'a': 1} dink['a'] +=1 dink
{'a': 2} dink['b']
0 dink['b']
0 dink
{'a': 2, 'b': 0}
Otherwise the usual ways are along the lines of
d = {} d.setdefault('h ello',[0])[0] += 1 d
{'hello': [1]} d.setdefault('h ello',[0])[0] += 1 d
{'hello': [2]}
Or d['hi'] = d.get('hi', 0) + 1 d
{'hi': 1, 'hello': [2]} d['hi'] = d.get('hi', 0) + 1 d
{'hi': 2, 'hello': [2]} d['hi'] = d.get('hi', 0) + 1 d
{'hi': 3, 'hello': [2]}
Or for x in xrange(3):
... try: d['yo'] += 1
... except KeyError: d['yo'] = 1
... print d
...
{'hi': 3, 'hello': [2], 'yo': 1}
{'hi': 3, 'hello': [2], 'yo': 2}
{'hi': 3, 'hello': [2], 'yo': 3}
Regards,
Bengt Richter
Hi,
In article <op************ **@news.telkoms a.net>, Caleb Hattingh wrote: ... Dict entries accessed with 'string' keys,
Not necessarily. And doesn't make a difference in my question.
...
Which feature specifically do you want justification for?
Have it your way: string-indexed dictionaries. a={} a['1']+=1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: '1'
a['1'] when it referenced, is detected non-existent but not
automatically initialized so that it exists before adding 1 to its
value.
Weiguang
Hi,
In article <41************ *****@news.oz.n et>, Bengt Richter wrote: On Thu, 25 Nov 2004 18:38:17 +0000 (UTC), wg***@namao.cs. ualberta.ca (Weiguang Shi) wrote: You wrote it, so you have to "justify" it ;-)
I guess :-)
While I agree that ++ and -- are handy abbreviations, and creating a key by default makes for concise notation, a[i]++ means you have to make some narrow assumptions ...
Right, though generalization can be painful for the uninitiated/newbie.
You can certainly make a dict subclass that behaves that way if you want it: ...
This is nice even for someone hopelessly lazy as me. Otherwise the usual ways are along the lines of ...
I would happily avoid them all.
Thanks a lot,
Weiguang
Hi
I apologise, but I don't actually know what the problem is? If you could
restate it a little, that would help.
I didn't check the code I posted earlier; This below is checked:
***
# Dont use a={}, just start as below
'>>> a['1']=0
'>>> a['1']+=1
'>>> a
{'1': 1}
***
Like I said, I am unsure of what your specific problem is?
Thanks
Caleb
On Thu, 25 Nov 2004 19:27:46 +0000 (UTC), Weiguang Shi
<wg***@namao.cs .ualberta.ca> wrote: Hi,
In article <op************ **@news.telkoms a.net>, Caleb Hattingh wrote: ... Dict entries accessed with 'string' keys, Not necessarily. And doesn't make a difference in my question.
...
Which feature specifically do you want justification for? Have it your way: string-indexed dictionaries.
>>> a={} >>> a['1']+=1
Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: '1'
a['1'] when it referenced, is detected non-existent but not automatically initialized so that it exists before adding 1 to its value.
Weiguang
And I haven't even been drinking!
I apologise once more, this is better:
***
# You *must* use a={}, just start as below
'>>> a={}
'>>> a['1']=0
'>>> a['1']+=1
'>>> a
{'1': 1}
***
Like I said, I am unsure of what your specific problem is?
Thanks
Caleb
I don't know awk, so I don't know how your awk statement works.
Even when it comes to the python statements, I'm not sure exactly what the
intentions of design intention were in this case, but I can see at least one
justification. Python being dynamically typed, b[1] can be of any type, so
you have to initialize b[1] to give it a type and only then adding something
to it makes sense. Otherwise, the 'add' operation not being implemented for
all types, 'b[1]+1' may not even be allowed.
You're saying that in awk a['hello'] is initialized to 0. 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.
Dan
"Weiguang Shi" <wg***@namao.cs .ualberta.ca> wrote in message
news:slrncqc9kq .hj3.wg***@nama o.cs.ualberta.c a... 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
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?
Weiguang
Hi,
In article <op************ **@news.telkoms a.net>, Caleb Hattingh wrote: ... *** # You *must* use a={}, just start as below '>>> a={}
Yeah I know. I can live with that.
'>>> a['1']=0 '>>> a['1']+=1
Right here. You have to say a['1'] = 0 before you can say a['1'] +=1
Python does not do the former for you. That's what I'm asking
justifications for.
Regards,
Weiguang This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
|
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...
|
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...
|
by: Benjamin Scott |
last post by:
Hello.
I attempted to build a compound dictionary:
len(Lst)=1000
len(nuerLst)=250
len(nuestLst)=500
Dict={}
|
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.
| |
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:
|
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)
|
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)
|
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...
|
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,...
|
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...
| |
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,...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |