Sono abbastanza nuovo per Python. Devo creare una classe che carichi i dati CSV in un dizionario.python csv nel dizionario
Voglio essere in grado di controllare i tasti e il valore Quindi diciamo il seguente codice, posso estrarre worker1.name o worker1.age ogni volta che voglio.
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
#
'''
Ma sono bloccato a caricare i miei dati csv in chiavi e valore.
[1] Voglio creare le mie chiavi worker1 = ageName ([nome], [età], [id], [sesso])
[2] ogni [nome], [età] , [id] e [genere] provengono da una specifica colonna in un file di dati CSV
Non so davvero come lavorare su questo. Ho provato molti metodi ma ho fallito. Ho bisogno di aiuto per iniziare.
---- Modifica Questo è il mio codice originale
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()
Questo è il mio codice corrente (incompleta)
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)
Si noti che se si desidera veramente un dizionario, non è possibile utilizzare 'worker1.name' per ottenere i valori. Si accede ai dizionari usando il modulo 'worker1 ['nome']'. Quindi, quale vuoi veramente? –
Ciao Peter. Mi dispiace e apprezzo molto il tuo commento. Questa è una bella domanda. Qualche pro e contro? Mi dispiace ... – CppLearner
Ci sono sempre pro e contro, ma hai chiesto un dizionario. Vuoi dire che non sai se dovresti usarne uno o no? Per rispondere, dovremmo capire di più su cosa farai con i dati. –