迭代Python中的字典和按类别的总和

时间:2016-12-01 02:16:46

标签: python loops dictionary

这个问题与这篇文章有关:

Iterate a Nested Dictionary in Python

作为后续行动,我试图对所有股票的总数进行求和,并按行业得出投资组合中股票的总百分比。

我希望输出看起来像这样:

技术:24%,财务:14%等等

我的字典看起来像这样:

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

我计算了每个股票的整体投资组合的总百分比,如下所示:

for stock_data in stockData.values():
    stock_data['percentage'] = stock_data['total']/stock_sum

并且我试图按行业获得%总数但却没有工作......我试过这个。

for stock_data in stockData.values():
    sector_totals = []
    for stock_data['sector'] in stock_data:
        sector_totals = (stock_data['sector'], stock_data['percentage'])

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以迭代stockData创建一个sector词典,该词典收集该行业的所有总计:

sectors = {}
for stock in stockData.values():
    sectors.setdefault(stock['sector'], []).append(stock['total'])
print(sectors)
# {'Technology': [300, 300]}

然后,您可以迭代stockData添加percentage

for stock in stockData.values():
    stock['percentage'] = stock['total']/sum(sectors[stock['sector']])

注意:在py2中,您必须将其中一个设为float,例如float(stock['total'])

或者,您可以为sector词典创建一个运行总计,这样可以避免上面的sum()

sectors = {}
for stock in stockData.values():
    sectors[stock['sector']] = sectors.get(stock['sector'], 0) + stock['total']
print(sectors)
# {'Technology': 600}

答案 1 :(得分:1)

任何不使用熊猫的理由? http://pandas.pydata.org/ 它会让你的生活更轻松。

我添加了一个额外的(假的)股票,以使该示例更具相关性。

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

import pandas as pd

# Create pandas dataframe wi
stockData_df = pd.DataFrame(stockData).T
stockData_df['percentage'] = stockData_df['total']/stockData_df['total'].sum()


stockData_df
Out[82]: 
         beta company_name dividend      sector total percentage
AAPL  1.01834        Apple  1.93417  Technology   300   0.333333
GOOG  1.01834        Apple  1.93417  Technology   300   0.333333
XXXX  1.01834        Apple  1.93417        Food   300   0.333333



sector_totals = stockData_df.groupby('sector').sum()['total']/stockData_df['total'].sum()

sector_totals
Out[86]: 
sector
Food          0.333333
Technology    0.666667
Name: total, dtype: float64