JSON导致API调用

时间:2016-10-21 02:00:36

标签: python json

如果我使用last.fm API包装器进行pylast,并查找similar tracks,请执行以下操作:

track = last.get_track('Radiohead', 'Karma Police')
    for similar in track.get_similar():
        print (similar)

我明白了:

SimilarItem(item=pylast.Track(u'Radiohead', u'No Surprises', pylast.LastFMNetwork('key', 'secret', 'string', 'user', 'string2')), match=1.0)
SimilarItem(item=pylast.Track(u'Radiohead', u'Paranoid Android', pylast.LastFMNetwork('key', 'secret', 'string', 'user', 'string2')), match=0.995)

如果我尝试索引它:

track = last.get_track('Radiohead', 'Karma Police')
    for similar in track.get_similar():
        print (similar[0])

我明白了:

Radiohead - No Surprises
Radiohead - Paranoid Android

我想以这种方式打印similar

         {
         "artist": "Radiohead",
         "track":"No surprises"
         },
         {
         "artist": "Radiohead",
         "track":"No surprises"
        }

但是如果我尝试similar[0][0],我会收到以下错误:

TypeError: 'Track' object does not support indexing

如何将结果构建为dictionary,然后呢?

1 个答案:

答案 0 :(得分:1)

如果你想要一本字典,你可以这样做:

track = last.get_track('Radiohead', 'Karma Police')
d = dict(str(item[0]).split(" - ") for item in track.get_similar())