[Tutor] Dictionary get method

Mitya Sirenef msirenef at lightbird.net
Wed Mar 20 14:13:28 CET 2013


On 03/20/2013 04:21 AM, Peter Otten wrote:
> Phil wrote:
>
>> On 20/03/13 15:09, Mitya Sirenef wrote:
>> <cut>
>>
>>> 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)
>>>
>> Thanks again Mitya, although I'm not sure it's a simplification at my
>> present level.
> Especially as Mitya's code doesn't work.


Ah, yes - I messed up here.. I agree the loop is the best option here,
vs. the example below. -m

>>>> d = {}
>>>> d.update((c, d.get(c, 0)+1) for c in "abba")
>>>> d
> {'a': 2, 'b': 2}
>
> but frankly, I don't see how that is better than the for loop.
>
> So as your experience with Python grows you may continue to use a loop or
> switch to the standard library's collections.Counter (Python3 only).
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


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



More information about the Tutor mailing list