[Baypiggies] How to create a dict of counts using functional programming

Marilyn Davis mdavis2 at ucsc.edu
Mon Sep 28 22:46:46 CEST 2015


I should add that using the standard library module is usually a better
idea because, hopefully, it runs in compiled C so is much faster, and there
are no bugs.

Marilyn Davis

On Mon, Sep 28, 2015 at 1:41 PM, Marilyn Davis <mdavis2 at ucsc.edu> wrote:

> It's a great little student project:
>
> data = '1','2','7','8','8'
>
> data_count_d = dict([(datum, data.count(datum)) for index, datum in
> enumerate(data) if index == data.index(datum)])
>
> print data_count_d
>
> That does it I think.
>
> Thanks for an interesting question.
>
> Marilyn
>
>
> On Mon, Sep 28, 2015 at 4:19 AM, David Berthelot <
> david.berthelot at gmail.com> wrote:
>
>> There's already a function written for that though in the standard
>> library:
>> https://docs.python.org/2/library/collections.html#collections.Counter
>>
>> On Mon, Sep 28, 2015 at 4:01 AM, Braun Brelin <bbrelin at gmail.com> wrote:
>>
>>> Hello all,
>>>
>>> I am trying to do the following:
>>> I have a list that looks like this:
>>> ['1','2','7','8','8']
>>>
>>> I want to create a dictionary that looks like this:
>>> {1:1, 2:1,7:1,8:2}
>>> i.e. the value is the count of the number of times the key appears in
>>> the list.  The catch is that I'm trying to do this in a functional
>>> programming way, rather than iteratively.
>>>
>>> I'm trying to use something like map, or reduce or even dict, but I
>>> can't figure out how to tell
>>> python to increment the value.  In other words how do I even specify
>>> what the value is, as it
>>> seems to be a bit of a chicken and egg scenario.
>>>
>>> I can, for example create a dictionary that sets the values to a
>>> constant, such as zero using FP,
>>> but how do I tell it to increment the value for a dictionary that
>>> doesn't yet exist as I'm in the process of
>>> building it?
>>>
>>> Thanks,
>>>
>>> Braun Brelin
>>>
>>>
>>>
>>> _______________________________________________
>>> Baypiggies mailing list
>>> Baypiggies at python.org
>>> To change your subscription options or unsubscribe:
>>> https://mail.python.org/mailman/listinfo/baypiggies
>>>
>>
>>
>> _______________________________________________
>> Baypiggies mailing list
>> Baypiggies at python.org
>> To change your subscription options or unsubscribe:
>> https://mail.python.org/mailman/listinfo/baypiggies
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20150928/925ab381/attachment.html>


More information about the Baypiggies mailing list