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

David Perlman dperlman at wisc.edu
Fri May 28 21:27:06 CEST 2010


Oh, except one problem: the csv.DictWriter lets you tell it what order  
you want the columns output in.  With your version, they just show up  
in whatever order Python wants them.

On May 28, 2010, at 2:33 AM, Peter Otten wrote:

> 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

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