python csv into dictionary

前端 未结 4 1720
感动是毒
感动是毒 2020-12-29 11:44

I am pretty new to python. I need to create a class that loads csv data into a dictionary.

I want to be able to control the keys and value So let say the following c

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 12:28

    import csv
    
    reader = csv.reader(open('workers.csv', newline=''), delimiter=',', quotechar='"')
    workers = [ageName(row[0], row[1]) for row in reader]
    

    workers now has a list of all the workers

    >>> workers[0].name
    'jon'
    

    added edit after question was altered

    Is there any reason you're using old style classes? I'm using new style here.

    class Student:
        sports = []
        def __init__(self, row):
           self.lname, self.fname, self.ID, self.sport = row
           self.sports.append(self.sport)
        def get(self):
           return (self.lname, self.fname, self.ID, self.sport)
    
    reader = csv.reader(open('copy-john.csv'), delimiter=',', quotechar='"')
    print "%-14s|%-10s|%-5s|%-11s" % tuple(reader.next()) # read header line from csv
    print "-" * 45
    students = list(map(Student, reader)) # read all remaining lines
    for student in students:
        print "%-14s|%-10s|%-5s|%3s" % student.get()
    
    # Printing all sports that are specified by students
    for s in set(Student.sports): # class attribute
        print s, Student.sports.count(s)
    
    # Printing sports that are not picked 
    allsports = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
    for s in set(allsports) - set(Student.sports):
        print s, 0
    

    Hope this gives you some ideas of the power of python sequences. ;)

    edit 2, shortened as much as possible... just to show off :P

    Ladies and gentlemen, 7(.5) lines.

    allsports = ['Basketball','Football','Other','Baseball','Handball',
                 'Soccer','Volleyball','I do not like sport']
    sports = []
    reader = csv.reader(open('copy-john.csv'))
    for row in reader:
        if reader.line_num: sports.append(s[3])
        print "%-14s|%-10s|%-5s|%-11s" % tuple(s)
    for s in allsports: print s, sports.count(s)
    

提交回复
热议问题