Iterate a Nested Dictionary in Python

后端 未结 3 1190
粉色の甜心
粉色の甜心 2021-01-29 00:20

My dictionary is structured as such:

stockData = {
    \'AAPL\': {
        \'beta\': 1.01833975315094,
        \'company_name\': \'Apple\',
        \'dividend\':         


        
相关标签:
3条回答
  • 2021-01-29 00:54

    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

    0 讨论(0)
  • 2021-01-29 00:57

    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')
    
    0 讨论(0)
  • 2021-01-29 01:00

    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
    
    0 讨论(0)
提交回复
热议问题