[英]Class objects (instances) into dictionary in Python
我想創建產品 Class 的多個實例,並將每個實例轉換為字典中的新項目。
我不太確定如何將 append 新的 object 及其屬性值添加到字典中
這是我的 class:
class Product():
def __init__(self, id, name, descr):
self.name = name
self.id = id
self.descr = descr
這是創建Product
對象並將它們插入字典的部分:
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)
所需的字典格式:
my_dict = {'1': {'id': '1', 'name': 'TestName1', 'descr': 'TestDescription1'}, '2': {'id': '2', 'name': 'TestName2', 'descr': 'TestDescription2'}, '3': {'id': '3', 'name': 'TestName3', 'descr': 'TestDescription3'}}
鑒於您想要的 output,我修改了我的答案。
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))
這將為您提供所需的格式,但我認為如果您的字典中有多個項目,您將遇到問題。
也許您想將它們存儲在列表而不是字典中,除非您對每個 object 都有一個鍵
products = []
products.append(Product(1, 'Test Name', 'Test Description'))
所以,如果你有鑰匙
products = {}
_id = 1
products[_id] = Product(_id, 'Test Name', 'Test Description')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.