data_garden data_garden - 1 month ago 5x
JSON Question

Python - iterate over JSON results

In order to get

values, I am trying to iterate over this

[{u'track_href': u'', u'analysis_url': u'', u'energy': 0.526, u'liveness': 0.0966, u'tempo': 92.979, u'speechiness': 0.103, u'uri': u'spotify:track:7603o589huckPbiELnUKgu', u'acousticness': 0.176, u'instrumentalness': 0.527, u'time_signature': 4, u'danceability': 0.635, u'key': 1, u'duration_ms': 172497, u'loudness': -8.073, u'valence': 0.267, u'type': u'audio_features', u'id': u'7603o589huckPbiELnUKgu', u'mode': 1},...}]

I'm using list comprehension:

[x['energy'] for x in features]

But I'm getting the following error:

print ([x['energy'] for x in features])
TypeError: 'NoneType' object has no attribute '__getitem__'

What am I doing wrong here?


It is because within your JSON array, at some place instead of dictionary a None value is present. You may eliminate it via:

[x['energy'] for x in features if x]