Reputation: 31
REFERENCE What can be the most efficient way to store and retrieve this type of table.
Product | Category | Original Price | Discount(%) |
---|---|---|---|
First | Stationary | 1000 | 10 |
Second | Clothing | 2000 | 5 |
stationary_items =[]
stationary_items.append({"Product" : "NOTEBOOK", "Category" : "STATIONARY", "Price" : 200, "Discount" : 20})
stationary_items.append({"Product" : "PENS", "Category" : "STATIONARY", "Price" : 300, "Discount" : 10})
stationary_items.append({"Product" : "MARKERS", "Category" : "STATIONARY", "Price" : 500, "Discount" : 5})
clothing_items = []
clothing_items.append({"Product" : "TSHIRT", "Category" : "CLOTHING", "Price" : 1000, "Discount" : 10})
clothing_items.append({"Product" : "JACKET", "Category" : "CLOTHING", "Price" : 2000, "Discount" : 5})
clothing_items.append({"Product" : "CAP", "Category" : "CLOTHING", "Price" : 500, "Discount" : 20})
I have to make queries later like if product is notebook then do something edit : I cannot use 3rd party libraries,
Upvotes: 1
Views: 164
Reputation: 176
Consider using NamedTuple
since you have a fixed set of keys (table headers).
You can use one-line factory:
Point = namedtuple('Point', ['x', 'y'])
or a class-like definition with type-hints:
class Employee(NamedTuple):
name: str
id: int
Both of this approaches gives your a nice hints for defined attributes and allows you to not pay hashing costs.
If you have a list of such namedtuples, than you can filter it like
[item for item in clothing_items if item.category == 'clothing' and product == 'tshirt']
,
it returns you a list of matching items.
You can describe a custom collection class, to store items hierarchically. smth like that (suppose that Product
is namedtuple describing a table row):
class ProductsByCategory:
def __init__(self):
self._products_by_category_map: dict[str, list[Product]] = defaultdict(list)
def add(product: Product):
self._products_by_category_map[product.category].append(product)
def __getitem__(self, category) -> [Product]:
return self._products_by_category_map[category]
Then list of products related to 'clothing'
category may be accessed like products_by_category['clothing']
.
With this approach you can go further and make it "product by product name map by category map", also you can control in add
method that there is only unique pairs of category and product name, so product_by_name_by_category['clothing']['tshirt']
may return you exactly one Product instance, instead of list of Product instances, so you can access it's .discount
field directly.
Keep in mind possibility of KeyError
while accessing products.
Upvotes: 1