我知道还有很多其他问题可以解答这个问题,但我想知道如何将CSV文件读入嵌套字典。所以它会是这样的:
'''"YEAR","GENDER","NAME","COUNT"
"2011","FEMALE","A","100"
"2012","FEMALE","A","50"
"2012","FEMALE","B","10"
"2012","FEMALE","C","10"
"2012","FEMALE","D","5"
"2013","FEMALE","A","1000"
'''
对于这样的事情:
{('B', 'FEMALE'): {2012: (10, None)},
('C', 'FEMALE'): {2012: (10, None)},
('A', 'FEMALE'): {2011: (100, None),
2012: (50, None),
2013: (1000, None)},
('D', 'FEMALE'): {2012: (5, None)}}
但我需要在不导入任何内容的情况下这样做,因此我无法使用CSV模块。这是一个普遍的例子;我需要使用该代码来处理可能比这个更长或更短的多个案例。
(总共有11个文件,这是其中之一,这里的文字与文件中的完全相同:
"YEAR","GENDER","NAME","COUNT"
"2011","FEMALE","A","100"
"2012","FEMALE","A","50"
"2012","FEMALE","B","10"
"2012","FEMALE","C","10"
"2012","FEMALE","D","5"
"2013","FEMALE","A","1000"
答案 0 :(得分:1)
answer = {}
with open('path/to/file') as infile:
infile.readline() # we don't care about the header row
for line in infile:
year, gender, name, count = (s.strip('"') for s in line.split(','))
key = (name, gender)
if key not in answer: answer[key] = {}
answer[key][int(year)] = (int(count), None)