我正在使用Spotipy从艺术家那里获取所有专辑。
对于每个查询,我都有以下Python字典对象(每个艺术家查询一个):
{
"href": "https://api.spotify.com/v1/artists/006ibfxHXj6ewIkihKcaS2/albums?offset=0&limit=1&include_groups=album",
"items": [
{
"album_group": "album",
"album_type": "album",
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/006ibfxHXj6ewIkihKcaS2"
},
"href": "https://api.spotify.com/v1/artists/006ibfxHXj6ewIkihKcaS2",
"id": "006ibfxHXj6ewIkihKcaS2",
"name": "Hello Meteor",
"type": "artist",
"uri": "spotify:artist:006ibfxHXj6ewIkihKcaS2"
}
],
"available_markets": [
"blabla"
],
"external_urls": {
"spotify": "https://open.spotify.com/album/19HZblBbWVWYVqiM0B9eW8"
},
"href": "https://api.spotify.com/v1/albums/19HZblBbWVWYVqiM0B9eW8",
"id": "19HZblBbWVWYVqiM0B9eW8",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/8c249db0add94460c7e61e994e7ac3f8f1abddd9",
"width": 640
},
{
"height": 300,
"url": "https://i.scdn.co/image/03ff6bd7c00fd58b167a4f3bc5529e5d17bf7ee1",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/151539b29846c6ae9b68c628e639d66277349468",
"width": 64
}
],
"name": "Mu & Mea",
"release_date": "2018-07-17",
"release_date_precision": "day",
"total_tracks": 15,
"type": "album",
"uri": "spotify:album:19HZblBbWVWYVqiM0B9eW8"
}
],
"limit": 1,
"next": "https://api.spotify.com/v1/artists/006ibfxHXj6ewIkihKcaS2/albums?offset=1&limit=1&include_groups=album",
"offset": 0,
"previous": null,
"total": 6
}
我有以下代码行将所有项目对象添加到列表中:
albums.extend(sp.artist_albums(artist, album_type='album', limit=1)['items'] for artist in artists)
问题是我只需要返回的两个无尽键即可;我只需要专辑标题和发行日期。我想要的输出是一个列表:
[['album name 1', 'release_date1'], ['album name2'', release_date2'], ...]
答案 0 :(得分:1)
而不是添加['items']
列表(如果我正确理解了limit=1
查询,列表仅包含一张专辑),而是添加具有特定值的新字典。
为避免必须为这两个项目调用两次Spotify API,请将您的查询循环放入generator expression;这样一来,便可以更轻松地提取生成的专辑字典并取出特定的键:
results = (result for artist in artists
for result in sp.artist_albums(artist, album_type='album', limit=1)['items'])
albums.extend([r['name'], r['release_date']] for r in results)
在这里,results
是{'album_group': ..., 'album_type', ..., ...}
字典的懒惰评估序列;这些是'items'
列表中所有要查询的歌手的专辑。这里的每个艺术家只有1个,但是在偶然的情况下可能会出现 zero 个专辑,或者您想提高limit
的值,因此请确保遍历所有项目。
albums.extend()
中的生成器表达式然后使用每个结果的两个键创建一个新的列表对象。