计算字典中不同键的值的数量

问题描述

我有一个看起来像这样的字典列表(它是从一个 json 文件创建的)

{"prizes":[{"year":"2020","category":"chemistry","laureates":[{"id":"991","firstname":"emmanuelle","surname":"Charpentier","motivation":"\"for the development of a method for genome editing\"","share":"2"},{"id":"992","firstname":"Jennifer A.","surname":"Doudna","share":"2"}]},{"year":"2020","category":"economics","laureates":[{"id":"995","firstname":"Paul","surname":"Milgrom","motivation":"\"for improvements to auction theory and inventions of new auction formats\"",{"id":"996","firstname":"Robert","surname":"Wilson","category":"literature","laureates":[{"id":"993","firstname":"Louise","surname":"Gl\u00fcck","motivation":"\"for her unmistakable poetic voice that with austere beauty makes individual existence universal\"","share":"1"}]}

etc.

我想要做的是计算每个类别的获奖者数量(知道在某些情况下有 0 个获奖者)

这是我想到的:

def nobel_data():
  with open('prize.json',newline='') as jsonfile:
    nobel = json.load(jsonfile)  

  counter = {} 
   
  for prize in nobel['prizes']:
    cat = prize['category']
    
    try: #'try' enables us to ignore the 'KeyError' with "pass".
      laureates = len(prize['laureates']) 
    except KeyError: 
      pass

    counter[cat] = counter.get(cat,0) + laureates 

  print(counter)

nobel_data()

但我想看看你们是否可以向我展示一种使用 setdefault 为每个可能的类别(化学、医学等)创建初始键的方法,然后找到每个类别的获奖者的 len

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...