Home > Blockchain >  Class objects (instances) into dictionary in Python
Class objects (instances) into dictionary in Python

Time:03-06

I would like to create multiple instances of the Product Class and convert 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 and inserts them into dictionary:

addProductToDict(id, name, descr, product_dict):

    new_product = Product(id, name, descr)

    # insert new product instance into dict
    product_dict <--- new_product ### pseudo code

    return product_dict

    
product_dict = {} 

while True:
    print(" Give the products id, name and description")
    id = input("Give id: ")
    name = input("Give name: ")
    descr = input("Give descr: ")

    product_dict = addProductToDict(id, name, descr, product_dict)
        

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