简体   繁体   中英

Python: CSV File to Dictionary without csv module

I know there are many other questions out there with the answer to this, but I want to know how to read a CSV file into a nested dictionary. So it would go from something like this:

    '''"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"
    '''

To something like this:

{('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)}}

But I need to do it without importing anything, so I can't use the CSV module. And this is a general example; I'd need the code to work for multiple cases that could be longer or shorter than this one.

(There are 11 files total, this being one of them, and the text here is exactly as it is in the file:

    "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"
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM