2017-05-29 54 views
-1

提取2個值我有以下的JSON:Python-從列表中的每個詞典],包含2所列出

{ 
"error": null, 
"page": "1", 
"per_page": "1000", 
"results": [ 
    { 
     "cves": [ 
      { 
       "cve_id": "CVE-2016-1583", 
       "href": "https://www.redhat.com/security/data/cve/CVE-2016-1583.html" 
      }, 
      { 
       "cve_id": "CVE-2016-5195", 
       "href": "https://www.redhat.com/security/data/cve/CVE-2016-5195.html" 
      } 
     ], 
     "description": "The kernel packages contain the Linux kernel, the core of any Linux operating\nsystem.\n\nSecurity Fix(es):\n\n* A race condition was With this update, a set of patches has been applied that fix\nthese problems. As a result, the time stamps of GFS2 files are now handled\ncorrectly. (BZ#1374861)", 
     "errata_id": "RHSA-2016:2124", 
     "hosts_applicable_count": 0, 
     "hosts_available_count": 0, 
     "id": "81ee41e6-2a3a-4475-a88e-088dee956787", 
     "issued": "2016-10-28", 
     "packages": [ 
      "kernel-2.6.18-416.el5.i686", 

     ], 
     "reboot_suggested": true, 
     "severity": "Important", 
     "solution": "For details on how to apply this update, which includes the changes described in\nthis advisory, refer to:\n\nhttps://access.redhat.com/articles/11258\n\nThe system must be rebooted for this update to take effect.", 
     "summary": "An update for kernel is now available for Red Hat Enterprise Linux 5.\n\nRed Hat Product Security 

我想提取errata_id和總結(只是RHEL版本) 的值,其我想放置的重新解釋,即:RHSA-2016:2098:紅帽企業Linux 5

我能提取errats名單,但不與總結作爲一個字典只是作爲一個列表:

ERRATA_ID_LIST = [] 
for errata_ids in erratas_by_cve_dic['results']: 
    ERRATA_ID = errata_ids['errata_id'] 
    ERRATA_ID_LIST.append(ERRATA_ID 
+0

你在尋找什麼樣的輸出?我無法理解你在這裏想問什麼 –

+1

你在這裏發佈的json不是有效的json。請檢查它 –

回答

1

如果我知道你想創建{ID,總結}一本字典,所以你可以做:

ERRATA_ID_DICT = {} 
for element in erratas_by_cve_dic['results']: 
    ERRATA_ID_DICT[element['errata_id']] = element['summary'] 
0

有兩種可能的方法:

1)使用for循環,像你這樣的,但將數據放入一個詞典:

errata = {} 
for errata_ids in erratas_by_cve_dic['results']: 
    errata_id = errata_ids['errata_id'] 
    summary = errata_ids['summary'] 
    errata[errata_id] = summary 

,或者更短但可能不太清楚:

errata = {} 
for errata_ids in erratas_by_cve_dic['results']: 
    errata[errata_ids['errata_id']] = errata_ids['summary'] 
使用字典解析10

2):

errata = { errata_ids['errata_id']: errata_ids['summary'] for errata_ids in erratas_by_cve_dic['results'] } 

我喜歡的第二方法更多,因爲它不僅是短,但也更Python(即。使用Python成語)。