On 2012-12-29 19:48, Quint Rankid wrote:
Newbie question.  I've googled a little and haven't found the answer.

Given a list like:
w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
I would like to be able to do the following as a dict comprehension.
a = {}
for x in w:
     a[x] = a.get(x,0) + 1
results in a having the value:
{1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}

I've tried a few things
eg
a1 = {x:self.get(x,0)+1 for x in w}
results in error messages.

And
a2 = {x:a2.get(x,0)+1 for x in w}
also results in error messages.

Trying to set a variable to a dict before doing the comprehension
a3 = {}
a3 = {x:a3.get(x,0)+1 for x in w}
gets this result, which isn't what I wanted.
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}

I'm not sure that it's possible to do this, and if not, perhaps the
most obvious question is what instance does the get method bind to?

You can't do it with a comprehension.

The best way is probably with the 'Counter' class:

>>> w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
>>> from collections import Counter
>>> Counter(w)
Counter({1: 3, 2: 2, 4: 2, 3: 1, 5: 1, 6: 1})

If you want the result be a dict, then just the result to 'dict':

>>> dict(Counter(w))
{1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to