get method

James Mills prologic at shortcircuit.net.au
Mon Dec 29 20:32:35 EST 2008


On Tue, Dec 30, 2008 at 11:00 AM, Ross <ross.jett at gmail.com> wrote:
> 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:
>
> Given:
>
> def histogram(s):
>    d = dict()
>    for c in s:
>        if c not in d:
>            d[c] = 1
>        else:
>            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
> example:
>
>>>> h = histogram('a')
>>>> print h
> {'a': 1}
>>>> h.get('a', 0)
> 1
>>>> h.get('b', 0)
> 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?

Ross, the others have informed you that you are not
actually incrementing the count. I'll assume you've
fixed your function now :) ... I want to show you a far
simpler way to do this which takes advantage of
Python's list comprehensions and mappings (which are
really what dictionaries are):

>>> s = "James Mills and Danielle Van Sprang"
>>> dict([(k, len([x for x in s if x == k])) for k in s])
{'a': 5, ' ': 5, 'e': 3, 'd': 1, 'g': 1, 'i': 2, 'M': 1, 'J': 1, 'm':
1, 'l': 4, 'n': 4, 'p': 1, 's': 2, 'r': 1, 'V': 1, 'S': 1, 'D': 1}
>>>

Let us know when you get to the "List Comprehension"
section - They are very powerful - As as Generators
and Generator Expressions.

Have fun learning Python,

cheers
James



More information about the Python-list mailing list