【问题标题】:Getting the value of a particular key from a dictionary inside nested list in Python从Python中嵌套列表内的字典中获取特定键的值
【发布时间】:2021-05-25 12:02:16
【问题描述】:

所以我试图从列表中的字典中解析 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字段。

【问题讨论】:

  • 当然会失败,.get 是 dict 方法,而不是 list 方法。如果您有一个列表,您要么需要直接使用索引访问字典,要么使用 for 循环迭代列表中的所有字典
  • 为什么不显示如何您尝试使用.get() 而不仅仅是说它不起作用?使用得当,你应该能够用它来得到你所追求的。

标签: python dictionary nested nested-lists


【解决方案1】:

要从您向我们展示的字典中获取您想要的数据,请执行以下操作:

>>> 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。那些仍在使用它的人这样做是因为我们必须支持或迁移遗留代码.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 2021-05-10
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多