简体   繁体   中英

Getting specific lines from a print in Python with Spotipy

I am writing some code with Python and Spotipy and I'm relatively new to coding. I have some code that get all the info about a Spotify playlist and prints it out for me:

from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import json


client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

playlist_id = 'spotify:playlist:76CVeJDw2b90up5PgkZXyU'
results = sp.playlist(playlist_id)
#print(json.dumps(results, indent=4))
print((json.dumps(results, indent=4)))

It works well and gives me all the info. My problem is that I only need specifics from the print:

  "collaborative": false,
    "description": "",
    "external_urls": {
        "spotify": "https://open.spotify.com/playlist/76CVeJDw2b90up5PgkZXyU"
    },
    "followers": {
        "href": null,
        "total": 0
    },
    "href": "https://api.spotify.com/v1/playlists/76CVeJDw2b90up5PgkZXyU?additional_types=track",
    "id": "76CVeJDw2b90up5PgkZXyU",
    "images": [
        {
            "height": 640,
            "url": "https://i.scdn.co/image/ab67616d0000b2734a052b99c042dc15f933145b",
            "width": 640
        }
    ],
    "name": "TEST",
    "owner": {
        "display_name": "Name",
        "external_urls": {
            "spotify": "https://open.spotify.com/user/myname"
        },
        "href": "https://api.spotify.com/v1/users/myname",
        "id": "Myname",
        "type": "user",
        "uri": "spotify:user:kovizsombor"
    },
    "primary_color": null,
    "public": true,
    "snapshot_id": "MixmMGE0MDgxNDQ1ZGVlNmE4MThiMmQwODMwYWU0OTI3YzkyOGJhOWIz",
    "tracks": {
        "href": "https://api.spotify.com/v1/playlists/76CVeJDw2b90up5PgkZXyU/tracks?offset=0&limit=100&additional_types=track",
        "items": [
            {
                "added_at": "2020-05-17T10:00:11Z",
                "added_by": {
                    "external_urls": {
                        "spotify": "https://open.spotify.com/user/kovizsombor"
                    },
                    "href": "https://api.spotify.com/v1/users/kovizsombor",
                    "id": "kovizsombor",
                    "type": "user",
                    "uri": "spotify:user:kovizsombor"
                },
                "is_local": false,
                "primary_color": null,
                "track": {
                    "album": {
                        "album_type": "album",
                        "artists": [
                            {
                                "external_urls": {
                                    "spotify": "https://open.spotify.com/artist/0PFtn5NtBbbUNbU9EAmIWF"
                                },
                                "href": "https://api.spotify.com/v1/artists/0PFtn5NtBbbUNbU9EAmIWF",
                                "id": "0PFtn5NtBbbUNbU9EAmIWF",
                                "name": "TOTO",
                                "type": "artist",
                                "uri": "spotify:artist:0PFtn5NtBbbUNbU9EAmIWF"
                            }
                        ],

                        ],
                        "external_urls": {
                            "spotify": "https://open.spotify.com/album/62U7xIHcID94o20Of5ea4D"
                        },
                        "href": "https://api.spotify.com/v1/albums/62U7xIHcID94o20Of5ea4D",
                        "id": "62U7xIHcID94o20Of5ea4D",
                        "images": [
                            {
                                "height": 640,
                                "url": "https://i.scdn.co/image/ab67616d0000b2734a052b99c042dc15f933145b",
                                "width": 640
                            },
                            {
                                "height": 300,
                                "url": "https://i.scdn.co/image/ab67616d00001e024a052b99c042dc15f933145b",
                                "width": 300
                            },
                            {
                                "height": 64,
                                "url": "https://i.scdn.co/image/ab67616d000048514a052b99c042dc15f933145b",
                                "width": 64
                            }
                        ],
                        "name": "Toto IV",
                        "release_date": "1982-04-08",
                        "release_date_precision": "day",
                        "total_tracks": 10,
                        "type": "album",
                        "uri": "spotify:album:62U7xIHcID94o20Of5ea4D"
                    },
                    "artists": [
                        {
                            "external_urls": {
                                "spotify": "https://open.spotify.com/artist/0PFtn5NtBbbUNbU9EAmIWF"
                            },
                            "href": "https://api.spotify.com/v1/artists/0PFtn5NtBbbUNbU9EAmIWF",
                            "id": "0PFtn5NtBbbUNbU9EAmIWF",
                            "name": "TOTO",
                            "type": "artist",
                            "uri": "spotify:artist:0PFtn5NtBbbUNbU9EAmIWF"
                        }
                    ],
                    "available_markets": [

                    ],
                    "disc_number": 1,
                    "duration_ms": 295893,
                    "episode": false,
                    "explicit": false,
                    "external_ids": {
                        "isrc": "USSM19801941"
                    },
                    "external_urls": {
                        "spotify": "https://open.spotify.com/track/2374M0fQpWi3dLnB54qaLX"
                    },
                    "href": "https://api.spotify.com/v1/tracks/2374M0fQpWi3dLnB54qaLX",
                    "id": "2374M0fQpWi3dLnB54qaLX",
                    "is_local": false,
                    "name": "Africa",
                    "popularity": 83,
                    "preview_url": "https://p.scdn.co/mp3-preview/dd78dafe31bb98f230372c038a126b8808f9349b?cid=d568e7073a38465bba48268ea9f10153",
                    "track": true,
                    "track_number": 10,
                    "type": "track",
                    "uri": "spotify:track:2374M0fQpWi3dLnB54qaLX"
                },
                "video_thumbnail": {
                    "url": null
                }
            }
        ],
        "limit": 100,
        "next": null,
        "offset": 0,
        "previous": null,
        "total": 1
    },
    "type": "playlist",
    "uri": "spotify:playlist:76CVeJDw2b90up5PgkZXyU"
}

From this long print I somehow need to extract the Artist and the song title and preferably make it into a variable. Also not sure how this would work if there are multiple songs in a playlist.

It's also a solution if I can print out only the Artist and the title of the song without printing out all the information.

sp.playlist returns a dictionary, so you can simply access its values by their keys. For example:

>>> results['name']
'TEST'

JSON is a data serialization format, ie a standardized way of representing objects as pure text and parsing them back from the text. json.dumps therefore converts the dictionary object to a string of text. This is useful if you want to for example save the results to a file and load it back later. You don't need it to access contents from results .

(This is a playlist though—you will need to get information on each song/track to get its artist and name.)

Based on your posted example it appears that you have only 1 song named "Africa" by artist "TOTO". Copying the track to have two songs, I added another track with two artists for testing the arrays.

If that json is loaded into a variable named results then (as @xcmkz said) you have a python dictionary and can process accordingly.

Try working with the following to transverse through your dict appending artists and songs to lists:

song_dict = {}
for track in results['tracks']['items']:
    song_name = track["track"]["name"]
    a2 = []
    for t1 in track['track']['artists']:
        a2.append(t1['name'])
        song_dict.update({song_name: a2})

print(f'Dictionary of Songs and Artists:')
for k, v in song_dict.items():
    print(f'Song --> {k}, by --> {", ".join(v)}')

Results:

Dictionary of Songs and Artists:
Song --> Africa, by --> TOTO
Song --> Just Another Silly Song, by --> Artist 2, Artist 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM