简体   繁体   English

在 Python 中迭代嵌套字典

[英]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.我遇到了一个问题,我在字典上使用 for 循环进行迭代以添加一个新值“百分比”,即“总数”除以所有股票的所有总数的总和。

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.问题是 get_portfolio_value 函数让我获得了投资组合的整个 portValue 总数,但是我试图将投资组合的百分比添加到每只股票的行不起作用 - 它只是奇怪地出现仅股票之一。 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 ):

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:为此,您可以将sum()用作:

     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:由于您不需要key ,请使用dict.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现在,您的stockData dict 的值以percentage持有附加键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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