Joh*_*ith 5 python csv dictionary python-3.x
我想从一个有两列的 csv 文件 (psc.csv) 中读取,如下所示:
cellname,scrambling
UER1100A,128
UER1100B,129
UER1100C,130
UER1300A,1
UER1300B,2
UER1300C,3
UER1400H,128
Run Code Online (Sandbox Code Playgroud)
并将整个文件放入一个字典中,这样字典将如下所示:
{'UER1100A': '128' , 'UER1100B': '129' , 'UER1100C': '130' , ...}
Run Code Online (Sandbox Code Playgroud)
我尝试使用csv
如下模块,但它返回混合输出并在单独的字典中。解决办法是什么?
我的代码:
#!/usr/bin/python3
import csv
with open('psc.csv', newline='') as pscfile:
reader = csv.DictReader(pscfile)
for row in reader:
print(row)
Run Code Online (Sandbox Code Playgroud)
只需将每一行添加到字典中:
import csv
results = {}
with open('psc.csv', newline='') as pscfile:
reader = csv.DictReader(pscfile)
for row in reader:
results[row['cellname']] = row['scrambling']
Run Code Online (Sandbox Code Playgroud)
而不是使用 a DictReader
,我会reader
在这里使用常规并dict()
在跳过第一行后将结果直接提供给调用:
import csv
with open('psc.csv',newline='') as pscfile:
reader = csv.reader(pscfile)
next(reader)
results = dict(reader) # pull in each row as a key-value pair
Run Code Online (Sandbox Code Playgroud)