[英]Get list of all values for a specific key in a list of nested dictionaries
我有这个列表,内容如下:
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]
您可以执行以下操作:
>>> [d['event']['magnitude'] for d in quake_list]
[1.3, 1.0]
要仅在记录是地震时记录震级,请使用:
>>> [d['event']['magnitude'] for d in quake_list if d['type'] == 'earthquake']
mag_list = [quake['event']['magnitude'] for quake in quake_list]
print(mag_list)
执行此指令时出现此错误:
mag=[d['event']['magnitude'] for d in quake_data if quake != None]
`TypeError: 'NoneType' object is not subscriptable`
我从整个文件中复制了一个小样本,长度为 131000,因此有 131000 个元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.