[Tutor] Dictionary get method

Mitya Sirenef msirenef at lightbird.net
Wed Mar 20 06:09:38 CET 2013


On 03/19/2013 10:54 PM, Phil wrote:
> Thank you for reading this.
 >
 > I'm working my way through a series of exercises where the author 
only provides a few solutions.
 >
 > The reader is asked to modify the histogram example so that it uses 
the get method thereby eliminating the if and else statements. 
Histogram2 is my effort.
 >
 > The resulting dictionary only contains the default value provided by 
"get" and I cannot see how the value can be incremented without an if 
statement.
 >
 > def histogram(s):
 > d = dict()
 > for c in s:
 > if c not in d:
 > d[c] = 1
 > else:
 > d[c] += 1
 > return d
 >
 > def histogram2(s):
 > d = dict()
 > for c in s:
 > d[c]= d.get(c, 0)
 >
 > return d
 >
 > h = histogram("brontosaurs")
 >
 > print h
 >
 > print
 >
 > print "histogram2"
 >
 > h = histogram2("brontosaurs")
 >
 > print h
 >

By the way, you can further simplify it by doing:

def histogram2(s):
     return {c: d.get(c,0)+1 for c in s}


That will work in python 3, in python 2 you need:

     return dict((c: d.get(c,0)+1) for c in s)


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Those who can make you believe absurdities can make you commit
atrocities.  Voltaire




More information about the Tutor mailing list