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

David Perlman dperlman at wisc.edu
Fri May 28 00:15:59 CEST 2010


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.  :)

Thanks!


--
-dave----------------------------------------------------------------
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard





More information about the Tutor mailing list