get method

Ross ross.jett at
Mon Dec 29 20:00:31 EST 2008

I am teaching myself Python by going through Allen Downing's "Think
Python." I have come across what should be a simple exercise, but I am
not getting the correct answer. Here's the exercise:


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

Dictionaries have a method called get that takes a key and a default
value. If the key appears in the dictionary, get returns the
corresponding value; otherwise it returns the default value. For

>>> h = histogram('a')
>>> print h
{'a': 1}
>>> h.get('a', 0)
>>> h.get('b', 0)

Use get to write histogram more concisely. You should be able to
eliminate the if statement.

Here's my code:

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?

More information about the Python-list mailing list