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

Brandon Beck bbeck at NOSPAM.austin.rr.com
Wed Jul 30 16:31:14 EDT 2003


Someone will definitely come up with a better solution than this, but
this could work for you at least as a first try

import types
def flatten(d, iterables=(types.ListType, types.TupleType)):
    rv = []
    for k, v in d.items():
        if type(v) in iterables:
            rv += [[k,x] for x in v]
        else:
            rv += [[k,v]]
    return rv

If you want to change the types of things that get iterated over, just
pass in a second parameter of your own.

Hope that helps,
Brandon



"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.
>
> Thanks in advance,
> Nicolas
>
>
>
> ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet
News==----
> http://www.newsfeed.com The #1 Newsgroup Service in the World!
>100,000 Newsgroups
> ---= 19 East/West-Coast Specialized Servers - Total Privacy via
Encryption =---






More information about the Python-list mailing list