Iterate through a dictionary of lists one "line" at a time

wswilson wswilson at gmail.com
Wed Apr 18 21:09:31 CEST 2007


On Apr 18, 2:54 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> On Apr 18, 7:39 pm, wswilson <wswil... at gmail.com> wrote:
>
>
>
> > Here is my code:
>
> > listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']}
>
> > I need to output:
>
> > id name
> > a Joe
> > b Jane
> > c Bob
>
> > I could do:
>
> > print 'id', 'name'
> > for id, name in zip(listing['id'], listing['name']): print id, name
>
> > but that only works if there are two entries in the dictionary, id and
> > name, and I know what they are. My problem is I don't know how many of
> > these entries there will be. Thanks for any help you can give!
>
> You can use zip(*sequence_of_sequences)
> eg zip(*[[1,2,3],[4,5,6]) returns [[1,4], [2,5], [3,6]]
> (You can think of it as a transposition function)
>
> For example:
>
> keys, item_lists = zip(*listing.iteritems())
> print " ".join(keys)
> for items in zip(*item_lists):
>     print " ".join(items)
>
> would work.
>
> HTH
>
> --
> Arnaud

That works perfectly. Thanks so much.




More information about the Python-list mailing list