Class objects (instances) into dictionary in Python

Question:

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 the 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 = {'1': {'id': '1', 'name': 'TestName1', 'descr': 'TestDescription1'}, '2': {'id': '2', 'name': 'TestName2', 'descr': 'TestDescription2'}, '3': {'id': '3', 'name': 'TestName3', 'descr': 'TestDescription3'}}
Asked By: devblack

||

Answers:

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.

Answered By: Matt

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'))

edit

so, if you have a key

products = {}
_id = 1
products[_id] = Product(_id, 'Test Name', 'Test Description')
Answered By: Diego Torres Milano
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.