简体   繁体   English

从 Python 的嵌套列表中的字典中获取特定键的值

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

So I'm trying to parse the SSL.cert.issuer & SSL.cert.subject fields from a dictionary inside a list, which is inside a dictionary.因此,我试图从列表中的字典中解析SSL.cert.issuerSSL.cert.subject字段,该列表位于字典中。 I tried using.item() &.get().我尝试使用.item() &.get()。 The get works for the key on the outside, but if I try to get() the value of something in a nested data field, it fails. get 适用于外部的键,但如果我尝试 get() 嵌套数据字段中某些内容的值,它会失败。

Sample dict:样本字典:

{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},

Can someone please help me with a pythonic way to get the data.SSL.cert.issuer & data.SSL.cert.subject fields from the above dict.有人可以帮我用pythonic的方式从上面的字典中获取data.SSL.cert.issuer & data.SSL.cert.subject 字段。

To get the data you want from the dict you have shown us, do this:要从您向我们展示的 dict 中获取您想要的数据,请执行以下操作:

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

If there is more than one element in the list a then you will need something like:如果列表a中有多个元素,那么您将需要以下内容:

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

which will get all of the certificate issuers in the data.这将获取数据中的所有证书颁发者。

As a side note, it appears you are using Python 2 (because Python 3 recognizes but ignores the string prefix u ).作为旁注,您似乎正在使用 Python 2 (因为 Python 3 识别但忽略字符串前缀u )。 If that is so, please bear in mind that as a beginner you should not be investing time in learning Python 2. Those of use who still work with it do so because we have to support or migrate legacy code.如果是这样,请记住,作为初学者,您应该花时间学习 Python 2. 仍在使用它的用户这样做是因为我们必须支持或迁移遗留代码。

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

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