【问题标题】:Python: sum all the values with same key in json?Python:对json中具有相同键的所有值求和?
【发布时间】:2020-11-15 11:46:26
【问题描述】:

我有一个我读过的 Json 文件。我会打印“total_signatures”的总和。

   {
        "response": [
            {
                
                "domains": [],
                "total_network_connections": 0,
                "total_processes": 0,
                "total_signatures": 0,
               
            },
            {
                "analysis_start_time": "2018-03-05 08:54:07",
                "avdetect": 52,
                "certificates": [],
                "classification_tags": [],
                "domains": [],
                "total_signatures": 55,
                "type": "PE32 executable (GUI) Intel 80386, for MS Windows",
                "type_short": [
                    "peexe",
                    "executable"
                ],
                "verdict": "malicious",
                "vxfamily": "Trojan.Agent"
            },
            {
                "analysis_start_time": "2016-05-18 09:10:50",
                "avdetect": 52,
                "certificates": [],
                "classification_tags": [],
                "total_signatures": 35,

..............

我试过这个但不起作用 ---> AttributeError: 'list' object has no attribute 'values'

  a = sum(d['total_signatures'] for d in data['response'].values() if d)

我该如何解决这个问题?谢谢

【问题讨论】:

  • 您的问题的答案取决于 json 的结构。请发布完整的详细信息。

标签: python json parsing


【解决方案1】:

试试这个

json = {...}
sum = 0
for i in json['response']:
    sum += (i['total_signatures'])
print(sum)

出来:

90

【讨论】:

  • 很高兴我能帮上忙
【解决方案2】:

应该这样做:

In [48]: d
Out[48]:
{'response': [{'domains': [],
   'total_network_connections': 0,
   'total_processes': 0,
   'total_signatures': 0},
  {'analysis_start_time': '2018-03-05 08:54:07',
   'avdetect': 52,
   'certificates': [],
   'classification_tags': [],
   'domains': [],
   'total_signatures': 55,
   'type': 'PE32 executable (GUI) Intel 80386, for MS Windows',
   'type_short': ['peexe', 'executable'],
   'verdict': 'malicious',
   'vxfamily': 'Trojan.Agent'},
  {'analysis_start_time': '2016-05-18 09:10:50',
   'avdetect': 52,
   'certificates': [],
   'classification_tags': [],
   'total_signatures': 35}]}

In [49]: sum([x['total_signatures'] for x in d['response']])
Out[49]: 90

【讨论】:

  • Nope :( ..i have this error--> TypeError: 'int' object is not callable
  • 也许你有一个名为“sum”的变量名。尝试以下操作: del sum 然后再次运行。在这个 oneliner 中调用的唯一函数是 sum。并且您建议的错误表明您将 int 类型变量作为函数调用,因此看起来是 sum。
  • 它非常非常大。我可以通过电子邮件发送给您吗?不,我没有总和变量:(
猜你喜欢
  • 2023-01-13
  • 1970-01-01
  • 2020-08-23
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
相关资源
最近更新 更多