2016-02-25 31 views
0

我有一個dict()所有在csv中找到的nmea句子。我試着創建另一個csv來將dict()的結果寫入其中以用於統計和記錄目的。但是,我不能因爲dict()不是「可調用的」嗎?你能轉換一個字典()爲一個序列嗎?

import csv 

#Counts the number of times a GPS command is observed 
def list_gps_commands(data): 
    """Counts the number of times a GPS command is observed. 

Returns a dictionary object.""" 

    gps_cmds = dict() 
    for row in data: 
     try: 
      gps_cmds[row[0]] += 1 
     except KeyError: 
      gps_cmds[row[0]] = 1 

    return gps_cmds 

print(list_gps_commands(read_it)) 
print ("- - - - - - - - - - - - -") 


with open('gpsresults.csv', 'w') as csvfile: 
    spamwriter = csv.writer(csvfile, delimiter=',', dialect='excel') 
    spamwriter.writerow(list_gps_commands(read_it)) 

有人能幫助我嗎?有沒有一種方法可以將鍵/值轉換爲序列,以便csv模塊可以識別它?或者另一種方式?

回答

1

使用csv.DictWriter而不是csv.writer

+0

我遠離我的電腦,我的工作是......'csv.DictWriter'會允許csv寫出整個字典表達式嗎? – Daniel

+0

它將在'DictWriter'構造函數的'fieldnames'參數中指定任何字段,不多不少。 – Amadan

+0

如果你在打印時得到結果{rmc:3,gga:5,gll:2},我會在csv中看起來像? – Daniel