1

I'm trying to import a CSV file data and define the first value of each line as a variable to a class object or a dict. I managed to create dictionaries from imported data, but can access them individually. Any enlightenment? Thank you.

CSV type:

name,gender,age,country,location

John,M,53,Brazil,São Paulo

import csv

file = "info.csv"
csv_open = open(file, newline="")
csv_data = csv.reader(csv_open)

data = []

for line in csv_data: # All CSV data as a list
    data.append(line)

class Person:

    """Simple register with name, gender, age, country and
    location info."""

    def __init__(self, name, gender, age, country, location):
        self.name = name
        self.gender = gender
        self.age = age
        self.country = country
        self.location = location

idx = 0

for elem in data:

    *problem_here_no_var* = Person( data[idx][0],
                                    data[idx][1],
                                    data[idx][2],
                                    data[idx][3],
                                    data[idx][4])
    idx += 1

print(John.country)
#My intention is to access a specific object and return any of it's attributes.
Lucas Coutin
  • 13
  • 1
  • 4

3 Answers3

0

According to Dathan Ault-McCoy, you can do this using the __ dict __ dictionary.

tkiral
  • 49
  • 1
  • 9
0

I would suggest using csv. Dictreader and either setting the headers yourself or just using your csv headers. Something like this

person_data = []
        with open(file, newline = '') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                temp_person = Person(row['name'], row['gender'], row['age'], row['country'], row['location'])
                person_data.append(temp_person)

Now you have a list of Person objects that have already been initialized and you can do whatever you want with that list after.

checkout https://docs.python.org/3/library/csv.html

DictReader and Writer get used fairly often.

as your code is now for the person object you need to add a

__str__ method so you can print the values of the person

example

def __str__(self):
return self.name + self.age.....

Now you can call

for person in person_data:
    print(person)
# can also do print(person.name) to get name can be done for any field.

And this will print whatever you defined in the str function.

0

You can set attributes on the current module dynamically. See How do I call setattr() on the current module?

The idea being that you use the string from the first column as the attribute name.

That being said, I'm not sure why you would need to set a variable to have an unknown name since it would be difficult to access it later without knowing it's name.

Josh J
  • 6,813
  • 3
  • 25
  • 47