从字典中获取信息的最佳方法

2024-10-01 04:46:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在绞尽脑汁寻找最好的方法来获得这个头衔,艺术家的名字

{'status': 'ok', 'results': [{'score': 0.94222, 'id': 'ca222fc1-d1ed-4c30-b21f-eb533cc909aa', 'recordings': [{'artists': [{'id': '84dc4f23-c0b8-4fe1-bbca-a3993ddc8fc2', 'name': 'Primus'}], 'id': '2f6227ba-e061-48b2-a700-15e209ed3650', 'title': 'Wynona’s Big Brown Beaver', 'duration': 264}, {'artists': [{'id': '84dc4f23-c0b8-4fe1-bbca-a3993ddc8fc2', 'name': 'Primus'}], 'id': '520ebd07-d12c-429c-a137-19d13303a706', 'title': 'Wynona’s Big Brown Beaver', 'duration': 261}, {'artists': [{'id': '84dc4f23-c0b8-4fe1-bbca-a3993ddc8fc2', 'name': 'Primus'}], 'id': '757439ce-58b1-4808-af3b-3b90092890c1', 'title': 'Wynona’s Big Brown Beaver', 'duration': 262}, {'artists': [{'id': '84dc4f23-c0b8-4fe1-bbca-a3993ddc8fc2', 'name': 'Primus'}], 'id': 'a432eaa4-e5bb-414a-9595-cdaa46d48d6e', 'title': 'Wynona’s Big Brown Beaver', 'duration': 264}, {'artists': [{'id': '84dc4f23-c0b8-4fe1-bbca-a3993ddc8fc2', 'name': 'Primus'}], 'id': 'c344a3f9-1755-4f1b-b227-8a5918713466', 'title': 'Wynona’s Big Brown Beaver', 'duration': 261}, {'artists': [{'id': '84dc4f23-c0b8-4fe1-bbca-a3993ddc8fc2', 'name': 'Primus'}], 'id': 'e658eb35-9d15-45d8-965c-1abcb19c8bc9', 'title': 'Wynona’s Big Brown Beaver', 'duration': 264}]}]}

我使用acoustic.match来匹配歌曲,上面的列表就是返回的内容

一定有比我做的更优雅的事情,那就是:

print(song['results'][0]['recordings'][0]['title'])

有什么建议吗

******编辑***** 所以-在进一步的回顾中-有一些示例代码,我正试图遵循-但似乎无法让它工作

for score, recording_id, title, artist in acoustid.match(apikey, path):

acousticid.match返回上面的字典/列表


Tags: nameidtitlematchresultsdurationbigbeaver
2条回答

你得到的数据是dict和list的混合体。由于列表只能通过索引访问,我不认为有更好的方法可以做到这一点,除非您预处理您的数据,以删除额外的嵌套列表

如果dict困扰着你,你可能想把它转换成一个类

class Music():

    def __init__(self, song):
        self.title = song['results'][0]['recordings'][0]['title']
        self.artist = song['results'][0]['recordings'][0]['artist'][0]['name']
        # and so on and so forth


new_song = Music(song)
>>> print new_song.artist
Primus
>>> print new_song.title
Wynona’s Big Brown Beaver

相关问题 更多 >