簡體   English   中英

Python:對 json 中具有相同鍵的所有值求和?

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

我讀了一個 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)

我該如何解決這個問題? 謝謝

這應該做:

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

試試這個

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

出去:

90

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM