interleaving dictionary values

Neil Cerutti horpner at yahoo.com
Tue Nov 21 16:35:12 CET 2006

```On 2006-11-21, j1o1h1n at gmail.com <j1o1h1n at gmail.com> wrote:
> I had in mind something like this:
>
>>>> interleave([1, 2, 3], [4,5], [7, 8, 9])
> [1, 4, 7, 2, 5, 8, 3, 9]
>
> [...] 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]

You can use itertools.chain instead of flatten:

>>> from itertools import chain
>>> filter(None, chain(*map(None, [1, 2, 3], [4, 5], [7, 8, 9])))
[1, 4, 7, 2, 5, 8, 3, 9]

> 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())

You need the * to "unpack" the list. It has generally taken the
place of apply.

>>> map(None, *d.values())
[(1, 7, 4), (2, 8, 5), (3, 9, None)]

> So... my bit of code becomes:

>>> filter(None, chain(*map(None, *d.values())))
[1, 7, 4, 2, 8, 5, 3, 9]

I don't think that the specific ordering that's achieved has any
valuable significance. You might be just as happy with the
simpler:

>>> list(chain(*d.values()))
[1, 2, 3, 7, 8, 9, 4, 5]

--
Neil Cerutti
Weight Watchers will meet at 7 p.m. Please use large double door at the side
entrance. --Church Bulletin Blooper

```