2

I'm new to Python and I'm using it to write a Spotify app with Spotipy. Basically, I have a dictionary of tracks called topTracks. I can access a track and its name/ID and stuff with

topSongs['items'][0]
topSongs['items'][3]['id']
topSongs['items'][5]['name']

So there's a function I'm trying to use:

recommendations(seed_artists=None, seed_genres=None, seed_tracks=None, limit=20, country=None, **kwargs)

With this function I'm trying to use seed_tracks, which requires a list of track IDs. So ideally I want to input topSongs['items'][0]['id'], topSongs['items'][1]['id'], topSongs['items'][2]['id'], etc. How would I do this? I've read about the * operator but I'm not sure how I can use that or if it applies here.

yhtrjdtryh
  • 73
  • 4
  • Check the updated answer if you are willing to use `*` or `**` operators while calling recommendations() function. – hygull May 04 '19 at 02:31

1 Answers1

3

You can try something like shown below.

ids = [item["id"] for item in topSongs["items"]]

Here, I have just formed a simple example.

>>> topSongs = {
...     "items": [
...         {
...             "id": 1,
...             "name": "Alejandro"
...         },
...         {
...             "id": 22,
...             "name": "Waiting for the rights"
...         }
...     ]
... }
>>> 
>>> seed_tracks = [item["id"] for item in topSongs["items"]]
>>> 
>>> seed_tracks
[1, 22]
>>> 

Imp note about using * operator »

* operator is used in this case but for that, you will need to form a list/tuple containing the list of data the function takes. Something like

You have to form all the variables like seed_tracks above.

data = [seed_artists, seed_genres, seed_tracks, limit, country]   

And finally,

recommendations(*data)

Imp note about using ** operator »

And if you are willing to use ** operator, the data will look like

data = {"seed_artists": seed_artists, "seed_genres": seed_genres, "seed_tracks": seed_tracks, "limit": limit, "country": country} 

Finally,

recommendations(**data)
hygull
  • 8,464
  • 2
  • 43
  • 52