[Tutor] Dictionary get method

Peter Otten __peter__ at web.de
Wed Mar 20 09:21:13 CET 2013


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.

>>> {k: v for k, v in [(1, "a"), (2, "b")]}
{1: 'a', 2: 'b'}

is called "dict comprehension", it builds a dict from a list of key-value 
pairs. However, there is no way to reference the resulting dict while it is 
being built, and that is necessary for a histogram. It is possible to use 
dict.update() with a generator expression

>>> 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).



More information about the Tutor mailing list