Home > Blockchain >  Save class object (instance) into dictionary in Python
Save class object (instance) into dictionary in Python

Time:03-05

I would like to create multiple instances of the Product Class and store each instance as a new item in a dictionary.

I'm not pretty sure how to append the new object and its attribute values to the dictionary

This is my class:

class Product():
    def __init__(self, id, name, descr):
        self.name = name
        self.id= id
        self.descr= descr

This is the part that creates the Product objects:

product_dict = {} 

new_product = Product(1, 'Test Name', 'Test Description')

product_dict.update.dict(new_student) # Trying to append the new object to dictionary
        

Desired dictionary format:

my_dict = {'id': 1, 'name': 'TestName', 'descr': 'TestDescr'}

CodePudding user response:

Given your desired output, I have modified my answer.

pprint(vars(new_product))

class Product():
    def __init__(self, id, name, descr):
        self.name = name
        self.id= id
        self.descr= descr

product_dict = {} 
new_product = Product(1, 'Test Name', 'Test Description')
product_dict = pprint(vars(new_product))

This will give you the desired format but I think you will have issues if you have more than one item in your dictionary.

CodePudding user response:

Perhaps you want to store them in a list instead of a dictionary, unless you have a key for each object

products = []
products.append(Product(1, 'Test Name', 'Test Description'))
  • Related