interleaving dictionary values
Tuomas
tuomas.vesterinen at pp.inet.fi
Wed Nov 22 17:49:56 EST 2006
j1o1h1n at gmail.com wrote:
> Hello,
>
> I was trying to create a flattened list of dictionary values where each
> value is a list, and I was hoping to do this in some neat functionally
> style, in some brief, throwaway line so that it would assume the
> insignificance that it deserves in the grand scheme of my program.
>
> I had in mind something like this:
>
>
>>>>interleave([1, 2, 3], [4,5], [7, 8, 9])
>
> [1, 4, 7, 2, 5, 8, 3, 9]
>
> I played for a while with zip(), [some newfangled python keyword, that
> I was truly shocked to find has been hiding at the bottom of the list
> built in functions since version 2.0], before giving up and going back
> to trusty old map(), long celebrated for making code hard to read:
>
>
>>>>map(None, [1, 2, 3], [4,5], [7, 8, 9])
>
> [(1, 4, 7), (2, 5, 8), (3, None, 9)]
>
> This is basically it. It then becomes:
>
>
>>>>filter(None, flatten(map(None, [1, 2, 3], [4,5], [7, 8, 9])))
>
> [1, 4, 7, 2, 5, 8, 3, 9]
>
> filter(None, - my brain parses that automatically now. This is not so
> bad. Flatten is snitched from ASPN/Cookbook/Python/Recipe/363051,
> thank you Jordan Callicoat, Mike C. Fletcher:
>
> def flatten(l, ltypes=(list, tuple)):
> i = 0
> while (i < len(l)):
> while (isinstance(l[i], ltypes)):
> l[i:i+1] = list(l[i])
> i += 1
> return l
>
> Trouble is then getting map() to play with the result of dict.values().
> I only worked this out while writing this post, of course.
>
> Given a dictionary like d = { "a" : [1, 2, 3], "b" : [4, 5], "c" : [7,
> 8, 9]} - I was hoping to do this:
>
> map(None, d.values())
>
> But instead I (finally worked out I could) do this:
>
> apply(map, tuple([None] + d.values()))
>
> So... my bit of code becomes:
>
> filter(None, flatten(map(None, apply(map, tuple([None] +
> d.values())))))
>
> It fits on one line, but it feels far more evil than I set out to be.
> The brackets at the end are bad for my epilepsy.
>
> Surely there is there some nice builtin function I have missed?
>
> --
> | John J. Lehmann, j1o1h1n(@)gmail.com
> + [lost-in-translation] "People using public transport look stern, and
> handbag
> + snatchers increase the ill feeling." A Japanese woman, Junko, told
> the paper:
> + "For us, Paris is the dream city. The French are all beautiful and
> elegant
> + And then, when we arrive..."
>
What about:
>>> d = { "a" : [1, 2, 3], "b" : [4, 5], "c" : [7, 8, 9]}
>>> L=[]
>>> for x in d.values(): L.extend(x)
...
>>> L
[1, 2, 3, 7, 8, 9, 4, 5]
or a little curious:
>>> L=[]
>>> map(L.extend, d.values())
[None, None, None]
>>> L
[1, 2, 3, 7, 8, 9, 4, 5]
TV
More information about the Python-list
mailing list