[Tutor] Dictionary get method
Phil
phil_lor at bigpond.com
Wed Mar 20 03:54:46 CET 2013
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
--
Regards,
Phil
More information about the Tutor
mailing list