簡體   English   中英

從 Python 的嵌套列表中的字典中獲取特定鍵的值

[英]Getting the value of a particular key from a dictionary inside nested list in Python

因此,我試圖從列表中的字典中解析SSL.cert.issuerSSL.cert.subject字段,該列表位於字典中。 我嘗試使用.item() &.get()。 get 適用於外部的鍵,但如果我嘗試 get() 嵌套數據字段中某些內容的值,它會失敗。

樣本字典:

{u'area_code': None,
 u'asn': u'',
 u'city': u'',
 u'country_code': u'RU',
 u'country_code3': None,
 u'country_name': u'Russian Federation',
 u'data': [{u'_id': u'XX',
            u'_shodan': {},
            u'asn': u'XX',
            u'cpe': [],
            u'cpe23': [],
            u'data': u'',
            u'domains': [u'XX'],
            u'hash': ,
            u'hostnames': [u'XX'],
            u'http': {},
            u'ip': XX,
            u'ip_str': u'XX',
            u'isp': u'XX',
            u'location': {},
            u'opts': {},
            u'ssl': {u'acceptable_cas': [],
                     u'alpn': [u'h2', u'http/1.1'],
                     u'cert': {u'expired': False,
                               u'expires': u'XX',
                               u'extensions': [{},{}],
                               u'fingerprint': {},
                               u'issued': u'XX',
                               u'issuer': {u'C': u'US',
                                           u'CN': u'R3',
                                           u'O': u"Let's Encrypt"},
                               u'subject': {u'CN': u'XX'},
                               u'version': 2},

有人可以幫我用pythonic的方式從上面的字典中獲取data.SSL.cert.issuer & data.SSL.cert.subject 字段。

要從您向我們展示的 dict 中獲取您想要的數據,請執行以下操作:

>>> a={u'area_code': None, ...etc...,
>>> print(a['data'][0]['ssl']['cert']['issuer'])
{'C': 'US', 'CN': 'R3', 'O': "Let's Encrypt"}

如果列表a中有多個元素,那么您將需要以下內容:

>>> for x in a['data']: 
        print(x['ssl']['cert']['issuer'])

這將獲取數據中的所有證書頒發者。

作為旁注,您似乎正在使用 Python 2 (因為 Python 3 識別但忽略字符串前綴u )。 如果是這樣,請記住,作為初學者,您應該花時間學習 Python 2. 仍在使用它的用戶這樣做是因為我們必須支持或遷移遺留代碼。

暫無
暫無

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

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