这是一个空字典
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']}}}
我是新手,请帮助我。
答案 0 :(得分:1)
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()]}
答案 1 :(得分:0)
您可以使用嵌套的collections.defaultdict
树并检查行是否足够长:
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:]
答案 2 :(得分:0)
更改"对于csv_reader中的列:" to" for csv_reader中的行:"
答案 3 :(得分:0)
直接地:
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']}}}