How to write two python dictionaries to a single csv?
Question: Can anyone please tell me how to write two `dict`s to a single csv? I tried
with one dict:

    
    
    import csv
    
    my_dict = {"test": 1, "testing": 2}
    
    with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
        w = csv.DictWriter(f, my_dict.keys())
        w.writeheader()
        w.writerow(my_dict)
    

But when I tried with two `dict`:

    
    
    import csv
    
    my_dict1 = {"test": 1, "testing": 2}
    my_dict2 = {"test": 3, "testing": 4}
    
    my_dict =my_dict1,my_dict2
    with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
        w = csv.DictWriter(f, my_dict1.keys())
        w.writeheader()
        w.writerow(my_dict)
    

That doesn't work :(

Thanks in advance


Answer: Just invoke `writerow` multiple times assuming they have the same keys.

    
    
    import csv
    
    my_dict1 = {"test": 1, "testing": 2}
    my_dict2 = {"test": 3, "testing": 4}
    
    with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
        w = csv.DictWriter(f, my_dict1.keys())
        w.writeheader()
        w.writerow(my_dict1)
        w.writerow(my_dict2)
    

