ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-Tutor
python-Tutor
Re: [Tutor] Detecting different list elements and counting them
by Terry Carroll other posts by this author
Dec 11 2003 11:07PM messages near this date
Re: [Tutor] Detecting different list elements and counting them | Re: [Tutor] Detecting different list elements and counting them
On Thu, 11 Dec 2003, Alan Gauld wrote:

>  my_dict = {}
>  for item in my_list:
>      if item in my_dict:
>         my_dict[item] += 1
>      else: my_dict[item] = 1

What I've done is:

my_dict = {}
for item in my_list:
    my_dict[item] = my_dict.get(item,0) + 1

my_dict.get returns the value of my_dict[item], if it exists, or zero if 
it does not; then you add one.

>  There might be a slightly cleverer way to do it using
>  my_dict(get)

This is probably what you had in mind.


-- 
Terry Carroll
Santa Clara, CA
carroll@[...].com 




_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Michael Grabietz
Alan Gauld
Terry Carroll
Zak Arntson
Edward Comber

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved