# get method

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Dec 30 03:02:16 CET 2008

```On Mon, 29 Dec 2008 17:38:36 -0800, Ross wrote:

> On Dec 29, 8:07 pm, Scott David Daniels <Scott.Dani... at Acm.Org> wrote:
>> Ross wrote:
>> > ... Use get to write histogram more concisely. You should be able to
>> > eliminate the if statement.
>>
>> > def histogram(s):
>> >    d = dict()
>> >    for c in s:
>> >            d[c]= d.get(c,0)
>> >    return d
>>
>> > This code returns a dictionary of all the letters to any string s I
>> > give it but each corresponding value is incorrectly the default of 0.
>> > What am I doing wrong?
>>
>> How is this code supposed to count?
>>
>> --Scott David Daniels
>> Scott.Dani... at Acm.Org
>
> I realize the code isn't counting, but how am I to do this without using
> an if statement as the problem instructs?

You don't increment a value using if. This would be silly:

# increment x
if x == 0:
x = 1
elif x == 1:
x = 2
elif x == 2:
x = 3  # can I stop yet?
else:
x = "I can't count that high!"

You increment a value using + 1:

x = x + 1

or

x += 1

In the original code, the program did this:

def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1

* look for c in the dict
* if it isn't there, set d[c] to 1
* but if it is there, increment d[c] by 1

def histogram(s):
d = dict()
for c in s:
d[c]= d.get(c,0)
return d

which is pretty much the same as:

* set d[c] to whatever d[c] already is, or 0 if it isn't already there.

So what you need is:

* set d[c] to whatever d[c] already is plus one, or 0 plus one if it