8-Bit Borges
8-Bit Borges

Reputation: 10033

JSON results in API calls

If I go about last.fm API, using pylast wrapper, and lookup for similar tracks, like so:

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

I get:

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)

if I try to index it:

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

I get:

Radiohead - No Surprises
Radiohead - Paranoid Android

I would like to print similar in this fashion:

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

but If I try similar[0][0], I get the following error:

TypeError: 'Track' object does not support indexing

How do I structure the result as a dictionary, then?

Upvotes: 1

Views: 81

Answers (1)

midori
midori

Reputation: 4837

If you want a dictionary you can do it this way:

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

Upvotes: 1

Related Questions