Writing multiple Python dictionaries to csv file
Question: Thanks to this other thread, I've successfully written my dictionary to a csv
as a beginner using Python: [Python: Writing a dictionary to a csv file with
one line for every 'key:
value'](http://stackoverflow.com/questions/8685809/python-writing-a-
dictionary-to-a-csv-file-with-one-line-for-every-key-value)

    
    
    dict1 = {0 : 24.7548, 1: 34.2422, 2: 19.3290}
    

csv looks like this:

    
    
    0  24.7548
    1  34.2422
    2  19.3290
    

Now, i'm wondering what would be the best approach to organize several
dictionaries with the same keys. I'm looking to have the keys as a first
column, then the dict values in columns after that, all with a first row to
distinguish the columns by dictionary names.

Sure, there are a lot of threads trying to do similar things, such as:
[Trouble writing a dictionary to csv with keys as headers and values as
columns](http://stackoverflow.com/questions/15440970/trouble-writing-a-
dictionary-to-csv-with-keys-as-headers-and-values-as-columns?rq=1) , but don't
have my data structured in the same way (yet…). Maybe the dictionaries must be
merged first.

    
    
    dict2 = {0 : 13.422, 1 : 9.2308, 2 : 20.132}
    dict3 = {0 : 32.2422, 1 : 23.342, 2 : 32.424}
    

My ideal output:

    
    
      ID  dict1    dict2    dict3
      0   24.7548  13.422   32.2422
      1   34.2422  9.2308   23.342
      2   19.3290  20.132   32.424
    

I'm not sure, yet, how the column name 'ID' for key names will work it's way
in there. Any help would be appreciated. Mahalo in advance!


Answer: Use `defaultdict(list)`

    
    
    from collections import defaultdict
    merged_dict = defaultdict(list)
    dict_list = [dict1, dict2, dict3]
    
    for dict in dict_list:
        for k, v in dict.items():
            merged_dict[k].append(v)
    

This is what you get:

    
    
    {0: [24.7548, 13.422, 32.2422], 1: [34.2422, 9.2308, 23.342], 2: [19.329, 20.132, 32.424]})
    

Then write the `merged_dict` to csv file as you had previously done for a
single dict. This time `writerow` method of `csv` module will be helpful.

