简体   繁体   English

Python:对 json 中具有相同键的所有值求和?

[英]Python: sum all the values with same key in json?

I have a Json file from i read.我读了一个 Json 文件。 i would to print the sum of 'total_signatures'.我想打印“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,

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

I tried with this but doesn't work ---> AttributeError: 'list' object has no attribute 'values'我试过这个但没有用 ---> AttributeError: 'list' object has no attribute 'values'

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

How can I solve This?我该如何解决这个问题? Thank you谢谢

This should do:这应该做:

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

try this试试这个

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

out:出去:

90

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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