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

Bengt Richter bokr at oz.net
Wed Jul 30 16:06:03 EDT 2003


On Wed, 30 Jul 2003 21:26:19 +0200, Nicolas Girard <Nicolas.nospam.Girard at removethis.nerim.net> wrote:

>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.
>
Assuming v3 and others like it can't be references to lists
(or how could you tell it from the format of k1's list?):

(I quoted your names to avoid haing to define them separately)

 >>> d = {'k1':['v1','v2'],'k2':'v3'}
 >>> flat = []
 >>> for k,v in d.items():
 ...     if isinstance(v,list):
 ...         for v2 in v:
 ...             flat.append([k,v2])
 ...     else:
 ...         flat.append([k,v])
 ...
 >>> flat
 [['k2', 'v3'], ['k1', 'v1'], ['k1', 'v2']]

Or would you prefer an inscrutable one-liner ;-)

Note that there is no guarantee of any particular order in d.items(),
though you could sort them:

 >>> d = {'k1':['v1','v2'],'k2':'v3'}
 >>> flat = []
 >>> items = d.items()
 >>> items.sort() # on keys
 >>> for k,v in items:
 ...     if isinstance(v,list):
             # Note that v is a list here, but does have pre-existing order you might want to keep.
             # If you wanted to guarantee sorted output of the v2's, you could
             # do v.sort() here, though you might surprise others holding references
             # to those lists, since they would see the sorting. To avoid that, make a copy first, e.g.,
             # v = v[:]; v.sort()  #(untested, but I think it should work ;-)

 ...         for v2 in v:
 ...             flat.append([k,v2])
 ...     else:
 ...         flat.append([k,v])
 ...
 >>> flat
 [['k1', 'v1'], ['k1', 'v2'], ['k2', 'v3']]

Regards,
Bengt Richter




More information about the Python-list mailing list