0

I have output from an object like this:

Item(Shoes, 79, 1, 'Smith',
Item(Shoes, 65, 1, 'Smith'
Item(T-Shirt, 19, 2, 'Smith'

Python:

all = []
def __init__(self, item: str, price: int, quantity: int, buyer: str):

    # Assign to self object
    self.item = item
    self.price = prive
    self.quantity = quantity
    self.buyer = buyer

    # Actions to execute
    Item.all.append(self)

@classmethod
def instantiate_from_csv(cls):
    df = pd.read_csv('items.csv', 
    sep=';', 
    usecols=["item", "price", "quantity", "buyer"])

    for index, item in df.iterrows():
        Item(
             item=str(item.get('item')),
             price=int(item.get('price')),
             quantity=int(item.get('quantity')),
             buyer=str(item.get('buyer')),
            )

def __repr__(self):
    return f"\nItem('{self.item}', {self.price}, {self.quantity}, '{self.buyer}')"

The data is gathered from a CSV file.

I want to sort the data like this:

Shoes:
-Smith, 1, 79$
-Smith, 1, 65$

T-Skirts:
-Smith, 2, 19$

I what this to be generated automatically (the unique categories should be found by the program). Is this possible with python objects?

Adrian Klaver
  • 15,886
  • 2
  • 17
  • 28
Shesch
  • 41
  • 6
  • 1
    if you define the `__lt__` method on your class then the instances will be sortable, e.g. you will be able to do `sorted([Item(...), Item(...), Item(...)])` https://stackoverflow.com/a/7152796/202168 and https://docs.python.org/3/reference/datamodel.html#object.__lt__ – Anentropic Oct 22 '22 at 14:51
  • 2
    you can also use https://docs.python.org/3/library/itertools.html#itertools.groupby to group them by `item` attribute – Anentropic Oct 22 '22 at 14:53

0 Answers0