[Tutor] Dictionary get method

Phil phil_lor at bigpond.com
Wed Mar 20 06:05:23 CET 2013


On 20/03/13 14:54, Amit Saha wrote:
> Hello Phil,
>
> On Wed, Mar 20, 2013 at 12:54 PM, Phil <phil_lor at bigpond.com> 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.
>
> You are almost there. Note that all you have to do is increment 1 to
> the current 'value' for the key denoted by c. If you change the line
> with get() to the following, it works as you want it to:
>
>   d[c]= 1 + d.get(c, 0)
>
> Output:
>
> {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1}
>
> histogram2
> {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1}
>
> You were almost there. Good Luck.
>
> -Amit.
>

Thanks Amit and Mitya,

I thought I must have been close.

I've played with C++ since the mid 90s and I'm finding Python very 
refreshing.

-- 
Regards,
Phil


More information about the Tutor mailing list