How to get spotipy playlist results in list format - python

I'm using spotipy to get a list of my playlists. I use
if token:
sp = spotipy.Spotify(auth=token)
playlists = sp.user_playlists(username)
for item in playlists['items']:
id= item['uri']
print id
This returns a list of playlist uri's that looks like
spotify:user:ultramusicofficial:playlist:0gvQoG7iMMz8L5Ltsa4lkT
spotify:user:spotify:playlist:4Ha7Qja6HY3AgvNBgWz87p
spotify:user:ministryofsounduk:playlist:7grWVkJDQpcBie8oqKP6hv
But there is something weird about the way it returns them. It's not a normal list and I can't seem to make it into one. If I use
print id[1]
It would return something like
p
p
p
I want to be able to do something like
print id[1]
and have it return
spotify:user:spotify:playlist:4Ha7Qja6HY3AgvNBgWz87p
I've tried joining it and splicing it in different ways, I've tried using it as a tuple, converting it to a string. Nothing works I'm clearly very unsure what to do. I feel like it's probably a simple and I'm just missing it. Any help would be appreciated thanks.

You are just printing the id, not gathering them into a list, so your id is the last item from the loop which is a single uri (a string). You can use a list comprehension to make a list out of the for loop:
id = [item['uri'] for item in playlists['items']]
Or start with an empty list and append the result to it:
id = []
for item in playlists['items']:
id.append(item['uri'])

In your example id is a string. So id[1] is the second character, which is p

Related

How do I get a normal list with strings instead of generator objects when I perform a googlesearch

Hi I am trying to get the first url of a google search based on queries in a list. For the sake of simplicity I am going to use the same code as a similar question 2 years prior.
from googlesearch import search
list_of_queries = ["Geeksforgeeks", "stackoverflow", "GitHub"]
results = []
for query in list_of_queries:
results.append(search(query, tld="co.in", num=1, stop=1, pause=2))
print (results)
Now this returns a list of generator objects. A solution was found to print out the list of results by adding
for result in results:
print (list(results))
However I want the results list to be in the form of a list of strings in order to web scrape the urls for data. One solution I found was to add
results_str = []
for result in results:
results_str.append(list(result))
When I print results_str I get this as an output:
[['https://www.geeksforgeeks.org/'], ['https://stackoverflow.com/'], ['https://github.com/']]
As one can see I cannot even use results_str directly as a list of urls to webscrape because of the additional brackets around each url. I thought I could work around it by removing the brackets by following this answer and thus adding
results_str_new = [s.replace('[' and ']', '') for s in results_str]
But this simply results in an AttributeError
AttributeError: 'list' object has no attribute 'replace'
Either way even if I did get it to work it all seems unnecessarily unnecessary to do all this work just to convert a list of generator objects to strings to use as urls to webscrape so I was wondering if there were any alternatives. I know that one of my options is to use selenium but I don't really want to do that because I don't want the hassle of an instance of Chrome opening whenever I run my script.
Thanks in advance
You are getting back a list of lists of string. To change that, you can use a list comprehension like this
results_str = [url for result in results for url in result]
or you can change from append to extend if you don't want to go with a list comprehension. Extend just extends the list where es append inserts the lists into the list.
results_str = []
for result in results:
results_str.extend(result)
Looks like you may be using a different version of googlesearch. I'm using googlesearch-python 1.1.0 so the call parameters are different. However, this should help:
from googlesearch import search
list_of_queries = ["Geeksforgeeks", "stackoverflow", "GitHub"]
results = []
for query in list_of_queries:
results.extend([r for r in search(query, 1, 'en')])
print(results)
Output:
['https://www.youtube.com/c/GeeksforGeeksVideos/videos', 'https://stackoverflow.com/', 'https://stackoverflow.blog/', 'https://github.com/']
Which, as you can see, is a simple list of strings (URLs in this case)

Add a unique id to list of nested dictionaries in python

I am working on a API request that return a list of nested dictionaries. The result is similar to this,
example=[{'transactionId':'1112234','customerID':1212,'total':360,'items':[{'productId':1a2345d23,'quantity':3,'price':160},{'productId':1a5645d99,'quantity':5,'price':200}],{
'transactionId':'11134674','customerID':1223,'total':120,'items':[{'productId':1a2345d27,'quantity':1,'price':60},{'productId':1a1145d22,'quantity':1,'price':60}}]]
I made a code to loop and append the newId to the list and was only able to insert the id to the parent dictionary.
result = [dict(item, newId= uuid.uuid4()) for item in example]
Any help would be greatly appreciated to attain my desire result like the one bellow.
example=[{'newId':1111,'transactionId':'1112234','customerID':1212,'total':360,'items':[{'newId':1111,'productId':1a2345d23,'quantity':3,'price':160},{'newId':1111,'productId':1a5645d99,'quantity':5,'price':200}],
{'newId':2222,'transactionId':'11134674','customerID':1223,'total':120,'items':[{'newId':2222,'productId':1a2345d27,'quantity':1,'price':60},{'newId':2222,'productId':1a1145d22,'quantity':1,'price':60}}]]
Your example data has syntax errors in it, so I wasn't able to test the following code, but I believe this is what you are looking for. You just need to do things the old fashioned way instead of doing list comprehension, and it becomes easy enough to do what you want.
result = []
for order in example:
order['newId'] = uuid.uuid4()
if 'items' in order:
for item in order['items']:
item['newId'] = uuid.uuid4()

creating list/tuple from string

Sorry if this has been asked,I wasnt able to find it. I am building a slackbot and was looking to be able to loop through inputted data. The user would entered in IDs and the script would loop through those ids and return values. I am able to get it working if a single ID is entered but I was looking to have it search multiple IDs at once.
Entered in slack
#SlackBot search id1,id2,id3
I tried to enter the info from the chat into a list separated by a comma but python treats every character as a new asset in the list. (i,d,1, ,i,d,2,..)
I was able to have the data entered into a dictionary and when printed it shows as
[id1,id2,id3]
So i tried to loop through the dictionary but it treats that string as one object and doesnt loop.
def assetSearch(enteredID):
idList =[enteredID.upper()]
searchedIDs = list()
for eid in idList:
print(eid) # This is here to see what its looking at
for k, v in Content.items():
if v['AssetID'] == eid:
the current print(eid) prints [id1,id2,id3] instead of id1, then id2.
Could someone point me in the correct direction?
You need to do
idList = enteredID.upper().split(",")

Pull url from string

I have the string below I'm trying to pull the url out of out with python django. Thoughts on how I can get to it? I've tried treating it like a list but didn't have any luck.
[(u'https://api.twilio.com/2010-04-01/Accounts/ACae738c5e6aaf12ffa887440a3143e55b/Messages/MM673cd77ab21b37ae435c1d1d5e767366/Media/ME33be4a0ae88358aaef2aa0ea25f31339', u'image/jpeg')]
It looks like your value is a list with one tuple with two items. So get the first of each using the 0th index:
lt = [(u'https://api.twilio.com/2010-04-01/Accounts/ACae738c5e6aaf12ffa887440a3143e55b/Messages/MM673cd77ab21b37ae435c1d1d5e767366/Media/ME33be4a0ae88358aaef2aa0ea25f31339', u'image/jpeg')]
url = lt[0][0]
print(url)
https://api.twilio.com/2010-04-01/Accounts/ACae738c5e6aaf12ffa887440a3143e55b/Messages/MM673cd77ab21b37ae435c1d1d5e767366/Media/ME33be4a0ae88358aaef2aa0ea25f31339
If your value is actually a string CONTAINING the list, you can get a list by using ast:
import ast
lt = ast.literal_eval(lt)
... then use the above code to access the inner contents of the list.

Convert web.py iterbetter to dictionary or list

I'm trying to get the some data from a MySQL table (ipb_members) using web.py's database.select. This is the code I'm using: members = db.select("ipb_members", where="name=\"asdfquerty\"")
it returns an instance of iterbetter. What I'm trying to figure out is how to convert that to a dictionary or a list. I saw this, which recommends using list(), but that just puts everything in the first index. I've also tried dict(), but that didn't work either. What am I doing wrong?
This should work:
members = db.select("ipb_members", where="name=\"asdfquerty\"")
for member in members #members is IterBetter
print member.posts #member is Storage
Note that you dont have to call .list() on the result of db.select if you need to iterate over it only once.
Have you tried dict(members)?
iterBetter is not very convenient as it can only iterate once, here is code convert iterBetter to list:
list_conv_from_db = []
for menber in menbers:
temp = dict()
for key in menber:
temp[key]=menber[key]
list_conv_from_db.append(temp)
then you get list_conv_from_db you can do everything you want!

Categories

Resources