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

Maric Michaud maric at aristote.info
Thu Apr 19 18:28:16 CEST 2007


wswilson a écrit :
> 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!
> 


The most simple and generic I see, it could be even more simple if you 
don't care of memory usage :

Let's fill a random dict :

In [118]: d=dict(zip((str(e) for e in xrange(10)), ([i**e for e in 
xrange(5)] for i in xrange(10))))

In [119]: d
Out[119]:
{'0': [1, 0, 0, 0, 0],
  '1': [1, 1, 1, 1, 1],
  '2': [1, 2, 4, 8, 16],
  '3': [1, 3, 9, 27, 81],
  '4': [1, 4, 16, 64, 256],
  '5': [1, 5, 25, 125, 625],
  '6': [1, 6, 36, 216, 1296],
  '7': [1, 7, 49, 343, 2401],
  '8': [1, 8, 64, 512, 4096],
  '9': [1, 9, 81, 729, 6561]}

go on :

In [146]: sorted_keys = tuple(sorted(d.keys()))

In [147]: from itertools import izip, chain

In [148]: sorted_keys = tuple(sorted(d.keys()))

In [149]: sorted_values = ( d[k] for k in sorted_keys )

In [150]: for vals in chain([sorted_keys], izip(*sorted_values)) :
    .....:     print '%5s'*len(d) % vals
    .....:
    .....:
     0    1    2    3    4    5    6    7    8    9
     1    1    1    1    1    1    1    1    1    1
     0    1    2    3    4    5    6    7    8    9
     0    1    4    9   16   25   36   49   64   81
     0    1    8   27   64  125  216  343  512  729
     0    1   16   81  256  625 1296 2401 4096 6561





-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 4 26 88 00 97
Mobile: +33 6 32 77 00 21



More information about the Python-list mailing list