简体   繁体   中英

python dicts into CSV

How to write python dictionaries of similar keys into csv, in which the keys becomes the header fields. For example:

dict1 =
  {
   key1: value1,
   key2: value2,
   key3: value3,
  }

dict2 =
  {
   key1: value4,
   key2: value5,
   key3: value6,
  }

  key1,key2,key3
  value1,value2,value3
  value4,value5,value6

If you like two more dicts,try this:

import csv

dict1 ={
   "key1": "value1",
   "key2": "value2",
   "key3": "value3"}

dict2 ={
   "key1": "value4",
   "key2": "value5",
   "key3": "value6"}

dict3 ={
   "key1": "value7",
   "key2": "value8",
   "key3": "value9"}

data = [dict1,dict2,dict3]

dict_writer = csv.DictWriter(file('my.csv','wb'),fieldnames=dict1.keys())
dict_writer.writeheader()
dict_writer.writerows(data)

Can you try like this:

#!/usr/bin/python

import csv

dict1 = {
   'key1': 'value1',
   'key2': 'value2',
   'key3': 'value3',
  }

with open('csv_test.csv', 'wb') as fh:
    w = csv.DictWriter(fh, dict1.keys())
    w.writeheader()
    w.writerow(dict1)

If you dictionaries are different, try the following:

import csv

dict1 = {1:'a',2:'b',3:'c'}
dict2 = {1:'aa',2:'bb',3:'cc'}
dict2[4] = 'dd'

keyset = set(dict1.keys() + dict2.keys())

with open('output.csv','w') as o:
    f = csv.writer(o)
    #write keys
    keylist = list(keyset)
    f.writerow(keylist)
    rowlist = []
    rowlist2 = []
    for i in keylist:   
        if i in dict1.keys():
            rowlist.append(dict1[i])
        else:
            rowlist.append('None')
        if i in dict2.keys():
            rowlist2.append(dict2[i])
        else:
            rowlist2.append('None')
    f.writerow(rowlist)
    f.writerow(rowlist2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM