[Tutor] Counting and grouping dictionary values in Python 2.7

Michael Selik michael.selik at gmail.com
Wed Jul 13 23:36:21 EDT 2016

On Fri, Jul 8, 2016 at 10:15 AM Bruce Dykes <bkd69ster at gmail.com> wrote:

> I'm compiling application logs from a bunch of servers, reading the log
> entries, parsing each log entry into a dictionary, and compiling all the
> log entries into a single list of dictionaries.

Seems reasonable. Perhaps instead of having each log entry as a dictionary,
you might prefer to create a namedtuple.

> Now, what I need to do with this arbitrarily count and total the values in
> the dictionaries, ie the total amount and number of items for transaction
> id 387, or the total number of crackers sold in NJ stores.

Use the Counter class from the collections module. Loop over your records,
write an if-statement to determine which records are interesting, then
increment the count for the appropriate key.

If you're having trouble, share your code and the error message.

Also, is there any particular advantage to pickling the list and having two
> files, one, the pickled file to be read as a data source, and the .csv file
> for portability/readability, as opposed to just a single .csv file that
> gets reparsed by the reporting script?

Probably simpler to keep just a CSV.

More information about the Tutor mailing list