2016-12-15 107 views
0

嘿我試圖通過使用內置模塊csv在python中創建一個字典。基本上它是一個名爲weather.csv的excel文件,其中行字典中的鍵是列標題,值是該行的值。我被卡住了,因爲我無法讓代碼運行多個列來同時生成兩個字典。此外,我得到一個關鍵的錯誤,它說打印行['col_list'],我不明白它爲什麼發生。 col_list是每行的標題。這是我的代碼到目前爲止:使用csv python行和列

import csv 
def read_file(filename, col_list): 
    filename = 'weather.csv' 
    with open('weather.csv', 'r') as f: 
     reader = csv.DictReader(f)  
     for row in reader:    
      print row['col_list'] 

這是我想我的輸出是。我認爲這很簡單,我錯過了,但我很難找出答案。

print read_file('weather.csv', ['TemperatureF', 'VisibilityMPH']) 
{'TemperatureF': [30.9, 32.0, 32.0, 32.0, 32.0, 30.9 ...], 
'VisibilityMPH': [10.0, 10.0, 10.0, 10.0, 4.0, 2.5 ...]} 
+0

這看起來很適合「熊貓」。試着用'pandas.read_csv'導入你的CSV文件,然後用'pandas.DataFrame.to_dict()'將其轉換成字典' – Jakub

+0

一些示例輸入數據可以使任何建議的答案更容易測試。 –

回答

1

怎麼樣創建一個包含每個列標題的鍵的字典和列包含的所有值的列表?例如 -

import csv 

def read_file(filename, col_list, data={}): 

    with open('weather.csv', 'r') as f: 

     reader = csv.DictReader(f)  
     for num, row in enumerate(reader): 
      if num == 0: continue # skip if it's the first row, which has the headings 
      for col in col_list: 
       if not data.get(col): data[col] = list() 
       data[col].append(row[col]) 

    return data 
+0

非常感謝 – Suzaku

0

如果你可以使用pandas,我認爲這將是一個更適合完成這個任務比csv模塊。

import pandas as pd 
df = pd.read_csv(filename, names=col_list) 
dict_ = df.to_dict()