繁体   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