Python : Writing a dictionary to a csv (short way)
Question: I am trying to write a dictionary to csv file, but not directly. I put a new
field name for dictionary keys.

The following does what I want, but I am wondering if it can be shortened?
Especially the last line.

    
    
    import csv
    
    mydict = {"John":{'car':'BMW','age':27}, 'Mike':{'car':'Jetta', 'age':35}}
    col_names = ['name','car','age']
    
    with open('junk', 'w' ) as f:
            writer = csv.DictWriter(f,fieldnames=col_names)
            writer.writeheader()
            for key, value in mydict.items():
                writer.writerow({'name':key, 'car':value['car'], 'age':value['age']}) # 
    

desired output should be:

    
    
    name,car,age
    Mike,Jetta,35
    John,BMW,27
    


Answer: To avoid repeating field names in the last line you can store data in a
temporary dictionary and update it:

    
    
    out = {'name':key}
    out.update(value)
    writer.writerow(out)
    

