简体   繁体   中英

Iterate a Nested Dictionary in Python

My dictionary is structured as such:

stockData = {
    'AAPL': {
        'beta': 1.01833975315094,
        'company_name': 'Apple',
        'dividend': 1.9341673320912078, 
        'total':300}, 
    'GOOG': {
        'beta': 1.01833975315094,
        'company_name': 'Apple',
        'dividend': 1.9341673320912078, 
        'total':300}
     }

and here is area where i assign values:

for row in range(2, sheet.max_row + 1):
    # Each row in the spreadsheet has data for one census tract.
    company_name  = sheet['A' + str(row)].value
    ticker = sheet['B' + str(row)].value
    sector = sheet['C' + str(row)].value
    shares = sheet['D' + str(row)].value
    price = sheet['E' + str(row)].value
    total = sheet['F' + str(row)].value
    beta = sheet['G' + str(row)].value
    dividend = sheet['H' + str(row)].value
    number_stocks+=1

    # Make sure the key for this ticker exists.
    stockData.setdefault(ticker,{})
    stockData[ticker]['company_name'] = company_name
    stockData[ticker]['sector'] = sector
    stockData[ticker]['shares'] = shares
    stockData[ticker]['price'] = price
    stockData[ticker]['total'] = total
    stockData[ticker]['dividend'] = dividend
    stockData[ticker]['beta'] = beta

I'm having an issue where i am iterating using a for loop over the dictionary to add a new value 'percentage' which is the 'total' divided by the sum of all the totals of all stocks.

def get_portfolio_value(stocks,item):
    portValue = 0
    percentage = 0
    for k, v in stocks.items():
        portValue = portValue + v.get(item,0)
        stockData[ticker]['percentage'] = stockData[ticker]['total']/portValue
    print(portValue)

get_portfolio_value(stockData,'total')

the issue is that the get_portfolio_value function is getting me the entire portValue total of the portfolio, but the line where i am trying to add the percentage of the portfolio to each stock isn't working righ--it is only oddly enough appearing for only one of the stocks. Can someone advise?

This is what you want:

stock_data = {
    'AAPL': {'beta': 1.01833975315094, 'company_name': 'Apple', 'dividend': 1.9341673320912078, 'total':300},
    'GOOG': {'beta': 1.01833975315094, 'company_name': 'Apple', 'dividend': 1.9341673320912078, 'total':300}
}

stock_sum = sum(stock_data[item]['total'] for item in stock_data)

for item in stock_data:
    stock_data[item]['percentage'] = int((float(stock_data[item]['total']) / stock_sum) * 100)

Result:

>>> for item in stock_data:
...     print stock_data[item]['percentage']
...
50
50

If I understand you question correctly, you may try as follows (I just copied the stockData below):

stockData = {
    'AAPL': {
        'beta': 1.01833975315094,
        'company_name': 'Apple',
        'dividend': 1.9341673320912078, 'total': 300},
    'GOOG': {
        'beta': 1.01833975315094,
        'company_name': 'Apple',
        'dividend': 1.9341673320912078, 'total': 300}}

I guess this is what you meant:

def get_portfolio_value(stocks, item='total'):
     portValue = 0
     for v in stocks.values():
        portValue += v[item]
     for k in stocks.keys():
        stocks[k].update({'percentage': stocks[k]['total'] / portValue})
    print(portValue)

get_portfolio_value(stockData, 'total')

Your problem can be solved in two parts:

  1. Take the sum of total stocks. For that you may use sum() as:

     stock_sum = sum(stock_data['total'] for stock_data in stockData.values())
  2. Iterate over the value to update the entry. Since you do not need key , use dict.values() to iterate over just the values:

     for stock_data in stockData.values(): stock_data['percentage'] = stock_data['total']/stock_sum # ^ Adds new key into your existing `dict` object

Now the values of your stockData dict holds additional key as percentage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM