[英]Python - Using column headings as keys for dictionary from csv file (without import module)
I must perform some calculations with values provided from a.csv file, and need to use the column headings as keys to their values in each column.我必须使用 .csv 文件提供的值执行一些计算,并且需要使用列标题作为每列中它们的值的键。 However there is a likelihood that the columns of the file may be jumbled up or swapped around, and thus simply indexing for the values of each key wouldn't work.
然而,文件的列有可能被打乱或交换,因此简单地为每个键的值建立索引是行不通的。 Also keeping in mind i cant import any modules such as csv. Heres a sample of what the csv file would look like, except with many more rows, and more AdultIDs...
另外请记住,我无法导入任何模块,例如 csv。这是 csv 文件的示例,除了更多的行和更多的 AdultIDs...
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 ![]() |
So effectively, I need the dictionary as such: {AdultID: [R7033, R7033, R7033], Landmark:[Ex_L, En_R, N, En_R]... } and so on.如此有效,我需要这样的字典:{AdultID: [R7033, R7033, R7033], Landmark:[Ex_L, En_R, N, En_R]... } 等等。
Assume that your input file (let's call it luh.csv) is a well formed CSV using commas as delimiters like this:假设您的输入文件(我们称之为 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
Then:然后:
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: 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.