dict comprehension question.

Joel Goldstick joel.goldstick at gmail.com
Sat Dec 29 15:15:39 EST 2012


On Sat, Dec 29, 2012 at 3:09 PM, Mitya Sirenef <msirenef at lightbird.net>wrote:

> On 12/29/2012 03:01 PM, Mitya Sirenef wrote:
>
>> On 12/29/2012 02:48 PM, 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?
> >>
> >> TIA
> >
> > Will this do?:
> >
> > >>> w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
> > >>> {x: w.count(x) for x in w}
> > {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}
> >
> >
> > - mitya
> >
>
> I should probably add that this might be inefficient for large lists as
> it repeats count for each item. If you need it for large lists, profile
> against the 'for loop' version and decide if performance is good enough
> for you, for small lists it's a nice and compact solution.
>
> In a more general case, you can't refer to the list/dict/etc
> comprehension as it's being constructed, that's just not a design goal
> of comprehensions.
>

Would this help:

     >>> w = [1,2,3,1,2,4,4,5,6,1]
     >>> s = set(w)
     >>> s
     set([1, 2, 3, 4, 5, 6])
     >>> {x:w.count(x) for x in s}
     {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}
>>>


>  -m
>
>
> --
> Lark's Tongue Guide to Python: http://lightbird.net/larks/
>
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121229/b6fc2617/attachment.html>


More information about the Python-list mailing list