[Tutor] list of dicts <-> dict of lists?

Peter Otten __peter__ at web.de
Fri May 28 09:33:24 CEST 2010


David Perlman wrote:

> Using the csv.DictReader and csv.DictWriter lets you read and write
> lists of dictionaries from files containing tabular data.  I have a
> system that naturally generates tabular data in the form of a
> dictionary of lists: the dictionary key is the name of the column, and
> then the value is a list which contains the data for that column.
> Sort of like a spreadsheet.  I would like to use csv.DictWriter to
> write out this data but that requires a list of dicts.
> 
> I can convert the dict of lists to a list of dicts, and thus make it
> compatible with csv.DictWriter, with the following ugly comprehensions:
> 
>  >>> y
> {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
>  >>> [dict([(i,y[i][j]) for i in y.keys()]) for j in
> range(len(y[y.keys()[0]]))]
> [{'a': 1, 'c': 7, 'b': 4}, {'a': 2, 'c': 8, 'b': 5}, {'a': 3, 'c': 9,
> 'b': 6}]
> 
> ...but I'm wondering if anyone knows of a more elegant way, perhaps
> something built-in suited for this purpose...
> 
> I am aware that any solution will only work if the lists in the dict
> are all the same length.  :)

I think it's simpler and therefore more appropriate to use a normal 
csv.writer here:

>>> import csv
>>> import sys
>>> data = {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
>>> writer = csv.writer(sys.stdout)
>>> writer.writerow(data.keys())
a,c,b
>>> writer.writerows(zip(*data.values()))
1,7,4
2,8,5
3,9,6

Peter



More information about the Tutor mailing list