[Tutor] setdefault method

Terry Carroll carroll at tjc.com
Tue Mar 28 02:22:30 CEST 2006


On Mon, 27 Mar 2006, Carroll, Barry wrote:

> So, what then is the proper use of setdefault()?  And, if d.setdefault
> does not actually assign a default value for d, is there a way to do
> this?

It's a somewhat misleading name, but setdefault a) looks up an entry in a 
dictionary and c) returns it... but if it's not found, between steps a & c
it b) sets the entry to the default value.

Think of it as a way to pre-initialize dictionary entries on the fly the 
first time they're referenced.

Here's an example, which looks at a string of text and creates a 
dictionary of the constituent characters' frequency:

>>> freq = {}
>>> sampletext = "norwegian blue"
>>> for char in sampletext:
...   freq[char] = freq.setdefault(char,0)+1
...
>>> freq
{'a': 1, ' ': 1, 'b': 1, 'e': 2, 'g': 1, 'i': 1, 'l': 1, 'o': 1, 'n': 2, 
'r': 1, 'u': 1, 'w': 1}
>>>




More information about the Tutor mailing list