[Tutor] Dictionary get method

Mitya Sirenef msirenef at lightbird.net
Wed Mar 20 05:54:29 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
 >


Add + 1

  -m


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

Whenever you find yourself on the side of the majority, it is time to
pause and reflect.  Mark Twain



More information about the Tutor mailing list