繁体   English   中英

遍历 Python 中嵌套字典中的所有值

[英]going through all values in nested dictionary in Python

我正在学习 Python 中的嵌套字典。 我需要找到 1997-98 和 2011-12 之间每个财政年度的平均支出,然后我需要按财政年度的时间顺序列出它们,格式为 xxxx-xx,只有当平均值大于零时。 然后我的结果应该看起来像 1997-98 (100,000,000)。平均值没有小数,即 100,000,000.10。

我的问题是:

  1. 自从我的 output 只显示一个结果以来,我怎么能在所有财政年度 go
  2. 如何在数字之间放置逗号(,)?
  3. 我怎样才能按时间顺序排列它们?

     for k,v in cleaned_data.items(): #iterate through all the record fin_year = v["fin_year"] if fin_year and v["expenditure"]: year = fin_year.split("-") if int(year[0]) >= 1997 and int(year[0]) <= 2011: total += int(v['expenditure']) count += 1 if count:= 0: average = (total/count) if average.= 0, print("Average health expenditure") print ('{} ({})':format(fin_year, average*100000)) else: pass

Cleaned_data 如下:

{'1':
{'fin_year': '1997-98','expenditure': '315'},
'2':
{'fin_year': None,'expenditure': '120'},
'3':
{'fin_year': '2000-01', 'expenditure': '314'},
'4':
{'fin_year': None, 'expenditure': None},
'5':
{'fin_year': '1997-98', 'expenditure': '12'}
}

在此处输入代码

您可以使用以下代码:

goal_years = list(range(1997, 2012))

result = dict()

for year in goal_years:

    total, count = 0, 0

    for k, v in cleaned_data.items():

        if v["fin_year"] and v["expenditure"]:

            if int(v["fin_year"].split("-")[0]) == year:

                total += int(v["expenditure"])

                count += 1

    if count:

        result['{}-{}'.format(year, str(year + 1)[-2:])] = total / count * 100000

if result:

    for k, v in result.items():

        print(k , "{:,}".format(int(v))) 

下面的代码集数字之间的逗号:

"{:,}".format(<number>)

我帮助它帮助你

暂无
暂无

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

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