Last Updated on March 30, 2023 by mishou

Work in progress.

I. What shall we learn?

If you are new to Dictionaries and Classes in Python, comparing Data Frames, Classes, and Dictionaries will help you understand Dictionaries and Classes better. Let’s create a data frame, a class, and a dictionary from the same sample data set. This is what I mean:

data frame dictionary

All the scripts are here:

II. Sample data set

The sample data set created with Faker:

sample data sete created with faker

III. Using Pandas

python code in Pandas

IV. Using Class

You can define a class with clean and simple codes using Data Classes.  You can learn Data Classes from the following post:

Why you should start using Python Dataclasses

# import a library
from dataclasses import dataclass
class Student:
  number: int
  name: str
  english: int
  mathematics: int

Unpack the data, create a class, instantiate objects with them and create a list of objects:

# create a list of objects
import csv
student_list = []
with open('exam.csv', newline='') as csv_file:
  reader = csv.reader(csv_file)
  next(reader, None) # skip the header
  # unpack the file
  for num, number, name, english, mathematics in reader:
    # convert the numbers to ints
    number = int(number)
    english = int(english)
    mathematics = int(mathematics)
    # create Student instances and append them to a list
    student_list.append(Student(number, name, english, mathematics))

V. Using Dictionary

By mishou

Leave a Reply

Your email address will not be published. Required fields are marked *