Re: new string formatting with local variables

2011-06-06 Thread Steve Crook
On Mon, 6 Jun 2011 12:15:35 -0400, Jabba Laci wrote in
Message-Id: :

> solo = 'Han Solo'
> jabba = 'Jabba the Hutt'
> print "{solo} was captured by {jabba}".format(solo=solo, jabba=jabba)
> # Han Solo was captured by Jabba the Hutt

How about:-

print "%s was captured by %s" % (solo, jabba)
-- 
http://mail.python.org/mailman/listinfo/python-list


Dictionaries and incrementing keys

2011-06-14 Thread Steve Crook
Hi all,

I've always done key creation/incrementation using:

if key in dict:
dict[key] += 1
else:
dict[key] = 1

Today I spotted an alternative:

dict[key] = dict.get(key, 0) + 1

Whilst certainly more compact, I'd be interested in views on how
pythonesque this method is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries and incrementing keys

2011-06-14 Thread Steve Crook
On Tue, 14 Jun 2011 05:37:45 -0700 (PDT), AlienBaby wrote in
Message-Id: <078c5e9a-8fad-4d4c-b081-f69d0f575...@v11g2000prk.googlegroups.com>:

> How do those methods compare to the one I normally use;
>
> try:
>  dict[key]+=1
> except:
>  dict[key]=1

This is a lot slower in percentage terms.  You should also qualify the
exception: except KeyError
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries and incrementing keys

2011-06-14 Thread Steve Crook
On Tue, 14 Jun 2011 13:16:47 +0200, Peter Otten wrote in
Message-Id: :

> Your way is usually faster than
>  
>> dict[key] = dict.get(key, 0) + 1

Thanks Peter, ran it through Timeit and you're right. It's probably also
easier to read the conditional version, even if it is longer.

> You may also consider
>
> http://docs.python.org/library/collections.html#collections.defaultdict
> http://docs.python.org/library/collections.html#collections.Counter

Useful functions, thanks again.
-- 
http://mail.python.org/mailman/listinfo/python-list