繁体   English   中英

循环计算嵌套的 JSON 对象

[英]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.

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