簡體   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