Reputation: 1
I have a dictionary that has multiple keys with multiple values and I want to store them into an object list rather than the dictionary. My results look like this:
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'}
I would like for these values to be store in an object that I have set up below:
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
How can I iterate through the keys and values of the dict so that I can store it in this class?
Upvotes: 0
Views: 126
Reputation: 4853
If you're using Python 3.7+, use dataclass
which accepts dict to initialize the object.
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)
But the only condition is dict should contain all the field names. You can also use default values in dataclass to avoid missing keys in dict problem.
Upvotes: 0