Dict to "flat" list of (key,value)

Raymond Hettinger vze4rx4y at verizon.net
Sat Aug 2 08:41:19 EDT 2003


"Nicolas Girard" <Nicolas.nospam.Girard at removethis.nerim.net> wrote in message
news:pan.2003.07.30.19.26.18.41642 at removethis.nerim.net...
> Hi,
>
> Forgive me if the answer is trivial, but could you tell me how to achieve
> the following:
>
> {k1:[v1,v2],k2:v3,...} --> [[k1,v1],[k1,v2],[k2,v3],...]
>
> The subtle point (at least to me) is to "flatten" values that are lists.

The other posters answered the question (as asked)
by showing a loop that differentiated the two cases
of inner lists vs single values.  One further thought,
is that the original data structure could be improved
by building it so that every value is in a list:

     {k1:[v1,v2],k2:[v3],...}

This is typically done by building the values with setdefault:

    index = {}
    for pagenum in range(len(pages)):
         page = pages[pagenum]
         for word in page:
               index.setdefault(word, []).append(pagenum)

The new structure is much more easily flattened:

      [(k,v) for k, values in newstruct.iteritems() for v in values]


it-all-starts-with-a-good-data-structure-ly yours,


Raymond Hettinger






More information about the Python-list mailing list