[英]loop to count nested JSON objects
我有一個學校作業(python 簡介,所以我開始了我的編碼之旅)我正在尋找一種更優雅的方式而不是硬編碼的方式來解決我遇到的問題。
問題:我有一份諾貝爾獎獲得者名單,我需要從 JSON 文件中計算每個類別的獲獎者總數。 所以,我需要從嵌套的 arrays 中計算嵌套的 JSON 對象。
JSON 鏈接: http://api.nobelprize.org/v1/prize.json
JSON 查看器: http://jsonviewer.stack.hu/
我的代碼目前給了我正確的 output,但它是硬編碼的。 假設我要在 X 年后重新做作業,並且有一個新的諾貝爾獎類別,我的程序將無法抓住它。 我知道我必須創建一個循環,這就是我苦苦掙扎的地方......我不確定如何從集合category_count
中創建一個循環,因為在集合中無法建立索引。
def nobel_data():
with open('prize.json', newline='') as jsonfile:
nobel = json.load(jsonfile)
category_count = set()
for prize in nobel['prizes']:
category_count.add(prize['category'])
dictio_cat = dict.fromkeys(category_count, 0)
dictio_cat['chemistry'] = sum([len(item["laureates"]) for item in nobel["prizes"] if item["category"] == 'chemistry' and "laureates" in item])
dictio_cat['economics'] = sum([len(item["laureates"]) for item in nobel["prizes"] if item["category"] == 'economics' and "laureates" in item])
dictio_cat['peace'] = sum([len(item["laureates"]) for item in nobel["prizes"] if item["category"] == 'peace' and "laureates" in item])
dictio_cat['physics'] = sum([len(item["laureates"]) for item in nobel["prizes"] if item["category"] == 'physics' and "laureates" in item])
dictio_cat['literature'] = sum([len(item["laureates"]) for item in nobel["prizes"] if item["category"] == 'literature' and "laureates" in item])
dictio_cat['medicine'] = sum([len(item["laureates"]) for item in nobel["prizes"] if item["category"] == 'medicine' and "laureates" in item])
print(dictio_cat)
output
{'physics': 216, 'medicine': 222, 'economics': 86, 'peace': 135, 'chemistry': 186, 'literature': 117}
我不是在尋找一個完整的解決方案,而是關於如何改進我的代碼的提示。 非常感謝!
您可以做的是使用collections.defaultdict
並創建所有類別的字典,並不斷添加獲勝者的總數(如果有的話)。
例如:
import collections
import requests
nobel_winners = requests.get("http://api.nobelprize.org/v1/prize.json").json()
total_laureates = collections.defaultdict(int)
for item in nobel_winners["prizes"]:
if "laureates" in item.keys():
total_laureates[item["category"]] += len(item["laureates"])
print(dict(total_laureates))
Output:
{'chemistry': 186, 'economics': 86, 'literature': 117, 'peace': 135, 'physics': 216, 'medicine': 222}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.