包含1 key 多 value 以及印出值
我們的資料包含列為標題與欄為標題兩種
列為標題(範例檔案)
Class | Name | ID |
2A | Amy | 135 |
1B | Ban | 145 |
建立字典時,我們希望能以標題為key,內容為值
import csv global mydict with open('D:/testfile.csv','rt') as fileX: filereader = csv.DictReader(fileX) mydict = {} for row in filereader: for column, value in row.items(): mydict.setdefault(column, []).append(value) for key in mydict: print('Key in mydict='+str(key)) for key in mydict.keys(): print('Key in d.keys='+str(key)) for value in mydict.values(): print('Key in d.values='+str(value)) for k,v in mydict.items(): print(k,v)
欄為標題(範例檔案)
Class | 2A | 1B |
Name | Amy | Ban |
ID | 135 | 145 |
import csv global mydict with open('D:/testfile.csv','rt') as fileX: filereader = csv.reader(fileX) mydict = {} for row in filereader: key = row[0] mydict[key] = row[1:] for key in mydict: print('Key in mydict='+str(key)) for key in mydict.keys(): print('Key in d.keys='+str(key)) for value in mydict.values(): print('Key in d.values='+str(value)) for k,v in mydict.items(): print(k,v)
以下印出的結果
(字典的key並沒有順序性,所以印出的順序有可能不一樣)
Key in mydict=ID Key in mydict=Class Key in mydict=Name Key in d.keys=ID Key in d.keys=Class Key in d.keys=Name Key in d.values=['135', '145'] Key in d.values=['2A', '1B'] Key in d.values=['Amy', 'Ban'] ID ['135', '145'] Class ['2A', '1B'] Name ['Amy', 'Ban']
需要特別注意的是
列為標題時,讀取檔案用的是
filereader = csv.DictReader(fileX)
欄為標題時,讀取檔案用的是
filereader = csv.reader(fileX)
Reference:
[1]: http://stackoverflow.com/questions/14091387/creating-a-dictionary-from-a-csv-file (Available:2016/02/23)
沒有留言:
張貼留言