简体   繁体   中英

Get list of all values for a specific key in a list of nested dictionaries

I have this list with contents below:

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'},
               ...]

Another thing, I need to filter out the None entries It seems, the file has none entries for this value.

That's why I get the error message

TypeError: list indices must be integers or slices, not str

I need to create a list named magnitude with all values for this:

magnitude = [1.3,1.0]

You can do the following:

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

To only record magnitudes if the record is an earthquake, use:

>>> [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)

I've this error when executing this instruction:

mag=[d['event']['magnitude'] for d in quake_data if quake != None]

`TypeError: 'NoneType' object is not subscriptable`

I've copied a small sample from the entire file which is 131000 length, so 131000 elements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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