将具有多个值的多个键的字典存储到类中

时间:2019-04-01 04:01:50

标签: python python-3.x

我有一个字典,其中有多个具有多个值的键,我想将它们存储到对象列表中而不是字典中。我的结果如下:

PLAB {'price': '9.450000', 'quantity': '8.0000', 'average_buy_price': '9.3000', 'equity': '75.60', 'percent_change': '1.61', 'equity_change': '1.200000', 'type': 'stock', 'name': 'Photronics', 'id': '2ae1c2e1-5c68-4d73-ba82-9d14fcf57fa6', 'pe_ratio': '16.187542', 'percentage': '5.63'}
CAIMMR {'price': '8.430000', 'quantity': '12.0000', 'average_buy_price': '8.4200', 'equity': '101.16', 'percent_change': '0.12', 'equity_change': '0.120000', 'type': 'stock', 'name': 'Immersion', 'id': 'bcf02154-1068-4f96-999a-f7ecd7724112', 'pe_ratio': '4.734742', 'percentage': '7.53'}
SH {'price': '19.680000', 'quantity': '4.0000', 'average_buy_price': '19.4400', 'equity': '78.72', 'percent_change': '1.23', 'equity_change': '0.960000', 'type': 'stock', 'name': 'Meta Financial', 'id': '7eb2c5f5-2c3c-46ec-b1d7-89c84c00b133', 'pe_ratio': '10.124530', 'percentage': '5.86'}

我希望将这些值存储在以下设置的对象中:

class StockProperties(object):
    def __init__(self, ticker, price, quantity, average_buy_price, equity, percent_change, equity_change, option_type, name, option_id, pe_ratio, portfolio_percentage):
        self.ticker = ticker
        self.price = price
        self.quantity = quantity
        self.average_buy_price = average_buy_price
        self.equity = equity
        self.percent_change = percent_change
        self.equity_change = equity_change
        self.type = option_type
        self.name = name
        self.option_id = option_id
        self.pe_ratio = pe_ratio
        self.portfolio_percentage = portfolio_percentage

如何遍历字典的键和值,以便将其存储在此类中?

2 个答案:

答案 0 :(得分:1)

您可以尝试:

class StockProperties(object):
    def __init__(self, *args, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

也许其他选择是使用DotMap

答案 1 :(得分:0)

如果您使用的是Python 3.7+,请使用接受字典的dataclass来初始化对象。

from dataclasses import dataclass
@dataclass
class StockProperties:
        ticker :str
        price :str
        quantity :str
        average_buy_price :str
        equity :str
        percent_change :str
        equity_change :str
        type :str
        name :str
        option_id :str
        pe_ratio :str
        portfolio_percentage :str

props = {'price': '9.450000', 'quantity': '8.0000', 'average_buy_price': '9.3000', 'equity': '75.60', 'percent_change': '1.61', 'equity_change': '1.200000', 'type': 'stock', 'name': 'Photronics', 'id': '2ae1c2e1-5c68-4d73-ba82-9d14fcf57fa6', 'pe_ratio': '16.187542', 'percentage': '5.63'}
stock = StockProperties(**props)

但唯一的条件是 dict 应该包含 all 字段名称。您也可以在数据类中使用默认值,以避免dict问题中键丢失。