【问题标题】:Get list of all values for a specific key in a list of nested dictionaries获取嵌套字典列表中特定键的所有值的列表
【发布时间】:2020-03-14 00:57:12
【问题描述】:

我有这个列表,内容如下:

quake_list = [{'time': '2016-01-12T21:05:59.000Z',
               'location': {'latitude': 60.5079, 'longitude': -142.9635},
               'event': {'magnitude': 1.3, 'depth': 9.1},
               'type': 'earthquake',
               'status': 'reviewed'},
              {'time': '2016-01-12T21:02:24.760Z',
               'location': {'latitude': 38.7978325, 'longitude': -122.7196655},
               'event': {'magnitude': 1.0, 'depth': -0.77},
               'type': 'earthquake',
               'status': 'automatic'},
               ...]

另外,我需要过滤掉 None 条目 看来,该文件没有该值的条目。

这就是我收到错误消息的原因

TypeError: 列表索引必须是整数或切片,而不是 str

我需要为此创建一个名为幅度的列表,其中包含所有值:

magnitude = [1.3,1.0]

【问题讨论】:

  • 这是一篇博文,您有问题吗? How to Ask
  • 请确保您已将代码附加到您的帖子中。这不是 SO 的工作方式(请使其干净)。

标签: python list dictionary filtering typeerror


【解决方案1】:

您可以执行以下操作:

>>> [d['event']['magnitude'] for d in quake_list]
[1.3, 1.0]

要仅在记录是地震时记录震级,请使用:

>>> [d['event']['magnitude'] for d in quake_list if d['type'] == 'earthquake']

【讨论】:

    【解决方案2】:
    mag_list = [quake['event']['magnitude'] for quake in quake_list]
    print(mag_list)
    

    【讨论】:

      猜你喜欢
      • 2014-11-27
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 2018-12-24
      相关资源
      最近更新 更多