creating list/tuple from string - python

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(",")

Related

How can i "reload" my string in a loop python

So i have some code pulling a unique id from a webpage, i then use that id in a loop and when its used i want it to get a new unique id, i know i can put the code pulling ids into the loop, but i use the code to tell the loop how long it should run. So is there anyway i can reload the id without putting all the code in the loop?
followrequestsnumber = jsonfollowrequests.count("\",\"username\"")
approveid = jsonfollowrequests[startapproveid:stopapproveid]
while followrequestnumber >=1:
uses the id on this line.
loop ends and now i want to switch the approveid to a new one
Why not something like this?
followrequestsnumber = jsonfollowrequests.count("\",\"username\"")
while followrequestnumber >=1:
approveid = jsonfollowrequests[startapproveid:stopapproveid]
followrequestsnumber = jsonfollowrequests.count("\",\"username\"")
...

Issue with a python string loop

So I'm having trouble getting my code to use a list of strings as inputs in a loop. Here's roughly what I have so far.
from arcgis.gis import GIS
Users = ['User01','User02','User03']
User_string = str(Users) # Have to do this as code needs input as string
gis = GIS("https://www.arcgis.com","USERNAME","PASSWORD") # This logs you into ArcGIS Online
User_role = 'org_user'
for x in User_string:
test = gis.users.get(username=x)
test.update_role(role=User_role)
print("Done! Check Web")
I just can't get the loop to work right. When I remove the for loop and put each user name in individually the get user and update role commands work just fine, it's just in the loop that is broken.
The two errors I'm getting is that the username has to be a string. I fixed that by adding the str() command, but I can't get the username to enter into the user.get loop.
Any suggestions? This code is actually looking at an excel file to produce the list of usernames so I can't just hardcode the list into the code. If it helps at all the website I've been using for the ArcGIS portion of the code is this one: https://developers.arcgis.com/python/guide/accessing-and-managing-users/
I should mention that I also tried just printing
test=gis.users.get(username=User_string)
And it came back as None. So I guess my question is how do I get 'User01' to go into the username=x spot?
Thanks much!
You're doing a for with the list as a string so it's looping on each character of the string. You need to do it with the original list.
Based on your code, you are telling your for loop to iterate on a String, since you converted your list to a string with User_string = str(Users); So the loop is going over each character on the string, which now it is User01User02User03
What you need to do is to iterate the list Users, like:
from arcgis.gis import GIS
Users = ['User01','User02','User03']
gis = GIS("https://www.arcgis.com","USERNAME","PASSWORD") # This logs you into ArcGIS Online
User_role = 'org_user'
for x in Users:
test = gis.users.get(username=x)
test.update_role(role=User_role)
print("Done! Check Web")

How do I properly format this API call?

I am making a telegram chatbot and can't figure out how to take out the [{' from the output.
def tether(bot, update):
tetherCall = "https://api.omniexplorer.info/v1/property/31"
tetherCallJson = requests.get(tetherCall).json()
tetherOut = tetherCallJson ['issuances'][:1]
update.message.reply_text("Last printed tether: " + str (tetherOut)+" Please take TXID and past it in this block explorer to see more info: https://www.omniexplorer.info/search")
My user will see this as a response: [{'grant': '25000000.00000000', 'txid': 'f307bdf50d90c92278265cd92819c787070d6652ae3c8af46fa6a96278589b03'}]
This looks like a list with a single dict in it:
[{'grant': '25000000.00000000',
'txid': 'f307bdf50d90c92278265cd92819c787070d6652ae3c8af46fa6a96278589b03'}]
You should be able to access the dict by indexing the list with [0]…
tetherOut[0]
# {'grant': '25000000.00000000',
# 'txid': 'f307bdf50d90c92278265cd92819c787070d6652ae3c8af46fa6a96278589b03'}
…and if you want to get a particular value from the dict you can index by its name, e.g.
tetherOut[0]['txid']
# 'f307bdf50d90c92278265cd92819c787070d6652ae3c8af46fa6a96278589b03'
Be careful chaining these things, though. If tetherOut is an empty list, tetherOut[0] will generate an IndexError. You'll probably want to catch that (and the KeyError that an invalid dict key will generate).

How to get spotipy playlist results in list format

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

Infinite For Loop issue in Python

I need to extract an ID from a JSON string that is needed for loading information into a MySQL database. The ID is a 5 or 6 digit number, but the JSON key that contains this number is the URL net_devices resource string that has the number at the end like this example:
{u'router': u'https://www.somecompany.com/api/v2/routers/123456/'}
Since there is not a key with just the ID, I have used the following to return just the ID from the JSON key string:
url = 'https://www.somecompany.com/api/v2/net_devices/?fields=router,service_type'
r = json.loads(s.get((url), headers=headers).text)
status = r["data"]
for item in status:
type = item['service_type']
router_url = item['router']
router_id = router_url.replace("https://www.somecompany.com/api/v2/routers/", "")
id = router_id.replace("/", "")
print id
This does indeed return just the ID values I want, and it doesn't matter if the result varies in the number of digits.
The problem: This code creates an infinite loop when I include the two lines above the print statement.
How can I change the syntax to allow the loop to run through all the returned IDs once, but still strip out everything except the numerical ID?
I am new to Python, and just starting to write code again after a very long hiatus since college. Any help would be greatly appreciated!
UPDATE
Thanks everyone for the feedback! With the help from David and Gerrat, I was able to find the issue that was causing the infinite loop and it was not this segment of the code, but another segment that was not properly indented. I am learning how to properly indent loops in Python, and this was one of my silly mistakes! Thanks again for the help!

Categories

Resources