Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 495249
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T05:34:31+00:00 2026-05-13T05:34:31+00:00

I am pretty new to python. I need to create a class that loads

  • 0

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 code, I can pull out worker1.name or worker1.age anytime i want.

class ageName(object):
'''class to represent a person'''
def __init__(self, name, age):
self.name = name
self.age = age

worker1 = ageName('jon', 40)
worker2 = ageName('lise', 22)

#Now if we print this you see that it`s stored in a dictionary
print worker1.__dict__
print worker2.__dict__
#
'''
{'age': 40, 'name': 'jon'}
#
{'age': 22, 'name': 'lise'}
#
'''
#

#when we call (key)worker1.name we are getting the (value)
print worker1.name
#
'''
#
jon
#
'''

But I am stuck at loading my csv data into keys and value.

[1] I want to create my own keys
worker1 = ageName([name],[age],[id],[gender])

[2] each [name],[age],[id] and [gender] comes from specific a column in a csv data file

I really do not know how to work on this. I tried many methods but I failed. I need some helps to get started on this.

—- Edit
This is my original code

import csv

# let us first make student an object

class Student():
    def __init__(self):
        self.fname = []
        self.lname = []
        self.ID = []
        self.sport = []
        # let us read this file
        for row in list(csv.reader(open("copy-john.csv", "rb")))[1:]:
            self.fname.append(row[0])
            self.lname.append(row[1])   
            self.ID.append(row[2])
            self.sport.append(row[3])
    def Tableformat(self):
        print "%-14s|%-10s|%-5s|%-11s" %('First Name','Last Name','ID','Favorite Sport')
        print "-" * 45
        for (i, fname) in enumerate(self.fname):
           print "%-14s|%-10s|%-5s|%3s" %(fname,self.lname[i],self.ID[i],self.sport[i])
    def Table(self):
        print self.lname

class Database(Student):
    def __init__(self):
        g = 0
        choice = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
        data = student.sport
        k = len(student.fname)
        print k
        freq = {}
        for i in data:
            freq[i] = freq.get(i, 0) + 1
        for i in choice:
            if i not in freq:
                freq[i] = 0
            print i, freq[i]


student = Student()
database = Database()

This is my current code (incomplete)

import csv
class Student(object):
    '''class to represent a person'''
    def __init__(self, lname, fname, ID, sport):
        self.lname = lname
        self.fname = fname
        self.ID = ID
        self.sport = sport
reader = csv.reader(open('copy-john.csv'), delimiter=',', quotechar='"')
student = [Student(row[0], row[1], row[2], row[3]) for row in reader][1::]
print "%-14s|%-10s|%-5s|%-11s" %('First Name','Last Name','ID','Favorite Sport')
print "-" * 45
for i in range(len(student)):
    print "%-14s|%-10s|%-5s|%3s" %(student[i].lname,student[i].fname,student[i].ID,student[i].sport)

choice = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
lst = []
h = 0
k = len(student)
# 23
for i in range(len(student)):
    lst.append(student[i].sport) # merge together

for a in set(lst):
    print a, lst.count(a)

for i in set(choice):
    if i not in set(lst):
        lst.append(i)
        lst.count(i) = 0
        print lst.count(i)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T05:34:31+00:00Added an answer on May 13, 2026 at 5:34 am
    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 😛

    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)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 269k
  • Answers 269k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Here are some of the advantages of MongoDB for building… May 13, 2026 at 1:20 pm
  • Editorial Team
    Editorial Team added an answer Lucene is decent, and probably easier than writing it yourself. May 13, 2026 at 1:20 pm
  • Editorial Team
    Editorial Team added an answer There are two possibilities. Either you defined beepAndLog as an… May 13, 2026 at 1:20 pm

Related Questions

The question: How do I create a python application that can connect and send
I'm trying to write (what I thought would be) a simple bash script that
The background I'm building a fair-sized web application with a friend in my own
I've been working on my own django based blog (like everyone, I know) to
I am pretty new to Python world and trying to learn it. This is

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.