dict generator question

George Sakkis george.sakkis at gmail.com
Thu Sep 18 17:52:11 CEST 2008


On Sep 18, 11:43 am, Gerard flanagan <grflana... at gmail.com> wrote:
> Simon Mullis wrote:
> > Hi,
>
> > Let's say I have an arbitrary list of minor software versions of an
> > imaginary software product:
>
> > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> > I'd like to create a dict with major_version : count.
>
> > (So, in this case:
>
> > dict_of_counts = { "1.1" : "1",
> >                    "1.2" : "2",
> >                    "1.3" : "2" }
>
> [...]
> data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> from itertools import groupby
>
> datadict = \
>    dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3]))
> print datadict

Note that this works correctly only if the versions are already sorted
by major version.

George



More information about the Python-list mailing list