[英]Python - How to Create Dictionary from CSV data file using column headings
[英]Python - Using column headings as keys for dictionary from csv file (without import module)
我必須使用 .csv 文件提供的值執行一些計算,並且需要使用列標題作為每列中它們的值的鍵。 然而,文件的列有可能被打亂或交換,因此簡單地為每個鍵的值建立索引是行不通的。 另外請記住,我無法導入任何模塊,例如 csv。這是 csv 文件的示例,除了更多的行和更多的 AdultIDs...
成人ID | 地標 | X | 是 | Z |
---|---|---|---|---|
R7033 | Ex_L | -32 | -39 | -4.6 |
R7033 | 恩_L | -1.8 | -41 | 6.7 |
R7033 | 否 | 12 | -34 | 22.6 |
R7033 | 恩_R | 30.1 | -43 | 8.3 |
如此有效,我需要這樣的字典:{AdultID: [R7033, R7033, R7033], Landmark:[Ex_L, En_R, N, En_R]... } 等等。
假設您的輸入文件(我們稱之為 luh.csv)是一個格式正確的 CSV,使用逗號作為分隔符,如下所示:
AdultID,Landmark,X,Y,Z
R7033,Ex_L,-32,-39,-4.6
R7033,En_L,-1.8,-41,6.7
R7033,N,12,-34,22.6
R7033,En_R,30.1,-43,8.3
然后:
with open('luh.csv') as csv:
columns = next(csv).strip().split(',')
dict_ = {}
for line in map(str.strip, csv):
for col, val in zip(columns, line.split(',')):
dict_.setdefault(col, []).append(val)
print(dict_)
Output:
{'AdultID': ['R7033', 'R7033', 'R7033', 'R7033'], 'Landmark': ['Ex_L', 'En_L', 'N', 'En_R'], 'X': ['-32', '-1.8', '12', '30.1'], 'Y': ['-39', '-41', '-34', '-43'], 'Z': ['-4.6', '6.7', '22.6', '8.3']}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.