Python 读取CSV数据并将其添加到字典中
这是一本空字典Python 读取CSV数据并将其添加到字典中,python,csv,dictionary,Python,Csv,Dictionary,这是一本空字典 d = {} 这是csv文件数据 M, Max, Sporting, Football, Cricket M, Jack, Sporting, Cricket, Tennis M, Kevin, Sporting, Cricket, Basketball M, Ben, Sporting, Football, Rugby 我尝试使用以下代码将csv中的数据附加到字典中 with open('example.csv', "r") as csvfile: csv_
d = {}
这是csv文件数据
M, Max, Sporting, Football, Cricket
M, Jack, Sporting, Cricket, Tennis
M, Kevin, Sporting, Cricket, Basketball
M, Ben, Sporting, Football, Rugby
我尝试使用以下代码将csv中的数据附加到字典中
with open('example.csv', "r") as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
if row:
d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
但这给了我一个错误:
d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
IndexError: list index out of range
在任何情况下,我都可以将csv中的数据添加到字典中,格式如下:
d = {'M': {'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}}}
我是新手,所以帮帮我吧
import csv
d={}
with open('JJ.csv', "r") as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
if row:
d.setdefault(row[0],{})[row[1]] = {row[2]: [row[3],row[4]]}
print(d)
{'M': {' Max': {' Sporting': [' Football', ' Cricket']}, ' Jack': {' Sporting': [' Cricket', ' Tennis']}, ' Kevin': {' Sporting': [' Cricket', ' Basketball']}, ' Ben': {' Sporting': [' Football', ' Rugby']}}}
要删除输出中的所有前导/尾随空格,可以使用下面的行。也许有更好的办法,我现在还不确定
d.setdefault(row[0],{})[row[1].strip()] = {row[2].strip(): [row[3].strip(),row[4].strip()]}
可以使用嵌套树并检查行是否足够长:
from collections import defaultdict
def tree():
return defaultdict(tree)
d = tree()
# ...
for row in csv_reader:
if len(row) >= 3:
d[row[0]][row[1]][row[2]] = row[3:]
将csv_读取器中的“列”改为“csv_读取器中的行:”直接:
import csv, collections
with open('example.csv', 'r') as f:
reader = csv.reader(f, skipinitialspace=True)
result = collections.defaultdict(dict)
for r in reader:
if not result[r[0]].get(r[1]): result[r[0]][r[1]] = {}
if not result[r[0]][r[1]].get(r[2]):
result[r[0]][r[1]][r[2]] = r[-2:]
print(dict(result))
输出:
{'M': {'Kevin': {'Sporting': ['Cricket', 'Basketball']}, 'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}, 'Ben': {'Sporting': ['Football', 'Rugby']}}}
您的循环变量是
列
,而不是行
,请看这里,为什么您的最终dict中遗漏了Kevin
和Ben
?更新您的问题这只是一个我希望字典看起来如何的示例您是否尝试打印有问题的行
?