仅向列表中插入Python嵌套字典的一些键
我用Spotipy从一个艺术家那里得到所有的专辑 对于每个查询,我都有以下Python dictionary对象(每个查询的艺术家一个): 我有以下代码行将所有items对象添加到列表中:仅向列表中插入Python嵌套字典的一些键,python,spotipy,Python,Spotipy,我用Spotipy从一个艺术家那里得到所有的专辑 对于每个查询,我都有以下Python dictionary对象(每个查询的艺术家一个): 我有以下代码行将所有items对象添加到列表中: albums.extend(sp.artist_albums(artist, album_type='album', limit=1)['items'] for artist in artists) 问题是我只需要两个返回的无止境键;我只需要专辑标题和发行日期。我想要的输出是一个列表: [['album n
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'], ...]
与其添加
['items']
列表(如果我正确理解您的limit=1
查询,它只包含一个相册),不如添加一个具有特定值的新词典
为了避免为这两项调用SpotifyAPI两次,请将查询循环放入;这样可以更轻松地获取生成的唱片集字典并取出特定的键:
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'
列表中的所有相册。这里每个艺术家只有一张专辑,但很可能没有专辑,或者你想提高限制值,我确保循环浏览这些项目
albums.extend()
中的生成器表达式创建了一个新的列表对象,其中每个结果有两个键。那么您想要什么样的输出呢?添加带有{'name':…,'release_date':…}
的词典,并且没有['items']['name']
,则'items'
键在列表中。您有['items'][0]['name']
。我想要一个只包含'name'
和'release\u date'
的列表,不包含键,只包含值。那么您最终得到的是嵌套列表吗<代码>[“专辑1标题”,“2018-07-17”],[“专辑2标题”,“2018-07-01”],…]
?您能否更新您的问题以显示预期输出?
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)