Python - Trying to use a range function to iterate through dictionary - python

response = requests.get('https://v2.jokeapi.dev/joke/Any?safe-mode&amount=5')
json_string = response.content
parsed_json = json.loads(json_string)
#part of the joke is that this code will sometimes run and sometimes not run. real funny if you ask me.
for i in range(4):
print("your jokes sir: ", parsed_json['jokes'][i]['setup'], parsed_json['jokes'][i]['delivery'])
I import 5 jokes and use a range of 4 to iterate through the separate instances of ['jokes'][i]['delivery'], I thought that this would cycle through the jokes, however it when it runs it doesn't always print the same amount, sometimes it doesnt print anything at all and constantly gives key errors. Wondering how to properly iterate through this
(i have tried changing the range number around and it doesnt seem to have any effect on hitting the key error)
(not using pandas or numpy cause this was for a class assignment and we did not use those for this assignment)

Not all jokes have the setup and delivery keys (I think the joke key and the setup delivery key pair to be mutually exclusive: there are jokes that consist of a whole joke string and jokes made of a setup and delivery) hence the error.
With dict.get() you can get values from dict while having a default value in case the key is missing:
for i, joke in enumerate(parsed_json['jokes']):
print(f"""joke #{i}: {joke.get('joke', '')}{joke.get('setup', '')} {joke.get('delivery', '')}""")
I printed the indexes just to be explicit, but you can use straight objects, and should use indexes only if necessary:
for joke in parsed_json['jokes']:
print(f"""your joke sir: {joke.get('joke', '')}{joke.get('setup', '')} {joke.get('delivery', '')}""")

Related

Confused on dictionary input example in Python Crash Course

I am working my way through Python Crash Course, and in Chapter 8 the author gives the following code as an example for filling a dictionary with user input. I am confused in the step where he stores the responses into the dictionary, as to my eye it looks as though he is only saving one piece of , "response" which is immutable data to the "responses" dictionary under the key "name". I am missing how both the name input and response input are put into the dictionary.
It seems to make no sense to me, but that is what I have loved about this journey so far, finding sense in seeming nonsense. Thank you for helping demystify this world for me.
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
#Prompt for the person's name and response.
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
#Store the response in the dictionary:
responses[name] = response
#Find out if anyone else is going to take the poll.
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat == 'no':
polling_active = False
#Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
The thing with dictionaries is that you can change the value of the key like this: dictionary[key] = value. If the key doesn't exist it will simply create a new key. You don't need any function like append which is used for lists. The line where you wrote responses[name] = response works because it stays in a while loop. After the loop runs again it asks another input and replaces the old name with a new name and old response with a new response. In conclusion, name and response is added every time the loop runs if the name is not already in the dictionary. If the name is there then it will simply change its value response if that is different from the old one.
Does this answer your question?
name and response are variables names that are filled with the inputted data, let's say 'John' and 'Kalimanjaro'.
Now, 'John' and 'Kalimanjaro' are indeed immutable, but that doesn't mean you can't replace the values stored in name and response in the next loop. You can assign a new value, maybe also immutable, to name if you want.
One possible source of confusion could be that you started learning dictionaries using statements like responses['John'] = 'Kalimanjaro', where both key and value were strings. Now you are doing responses[name] = response (no quotes around name and response). So you create a key called whatever was stored in name and a value with whatever was stored in response.
If in the next iteration the value of name is replaced by, let's say 'Maria' and response becomes 'Andes', the new responses[name] = response will be equivalent to responses['Maria'] = 'Andes'.
In the most basic explanation, dictionaries associates an arbitrary value at an arbitrary key. So, what the author is actually doing is associating the user's response with their name. The author does this by using the name as a key and the response as a value. Using dictionaries like this is fairly common.
If you want to retrieve a value in the array, you must know it key. However, you can retrieve all key and value pairs with dictionary.items(). This way, the author can get those two associated pieces of data (the name and the response).

Find IP address which occurs most frequent and count the number of times that it appears

Hi all First time having to look for assistance but i am sort of at a brick wall for now. i have been learning python since August and i have been giving a challenge to complete for the end of Novemeber and i hope that there could be some help in making my code works. My task requires to find an ip address which occurs most frequent and count the number of times it appears also this information must be displayed to the user i have been giving 4 files .txt that have the ips. I am also required to make use of non trivial data structures and built in python sorting and/or searching functionalities, make use of functions, parameter passing and return values in the program. Below is a sample data structure they have recommended that i use: -
`enter code here`
def analyse_logs(parameter):
# Your Code Hear
return something
def extract_ip(parameter):
# Your Code Hear
return something
def find_most_frequent(parameter):
# Your Code Hear
return something
# Test Program
def main():
# Your Code Hear
# Call Test Program
main()
And below hear is what i have came up with and the code is completley differant from the sample that has been provided but what i have done dosnt give me output straight back instead creats a new text file which has been sorted but now what i am looking for: -
enter code here
def sorting(filename):
infile = open(filename)
ip_addr = []
for line in infile:
temp = line.split()
for i in temp:
ip_addr.append(i)
infile.close()
ip_addr.sort()
outfile = open("result.txt", "w")
for i in ip_addr:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample_log_1.txt")e here
The code that i have created has sorted everything thats in the .txt file and outputs the most frequent that has been used all the way to the lest frequent. All i am look for is for an algorithim that can sort through the .txt file, find the IP address thats more frequent then print that ip out and how many times it appears. I hope i have provided everything and i am sure this is probally somthing very basic but i just cant get my head round it.
You should keep the number of times the IP addresses are repeated in a variable. You can use dictionary.
ip_count_dict = {"IP1": repeat_count, "IP2": repeat_count}
When first time you find a IP in your list set repeat_count 1 and after that if you find same ip again just increase counter.
For example,
ip_count_dict = {}
ip_list = ['1.1.1.1','1.1.1.2','1.1.1.3','1.1.1.1']
#Loop and count ips
#Final version of ip_count_dict {'1.1.1.1':2 , '1.1.1.2':1, '1.1.1.3':1}
With this dictionary you can store all ips and sort by their value.
P.S.: Dictionary keeps key,value pairs you can search "sort dictionary by value" after all counting thing done.

Python list.append not working. I'm using discord.py and replit database to make a gambling bot and I wanted a list of participants

So basically I'm trying to get a discord betting bot to give a list of participants that it can cycle through when games end. The problem is that when I use this code it doesn't seem to append. I've tried debugging it using an alt. The not in db['list'] part triggers fine, and there are no errors raised, but the list still only contains my main account's ID (which was used to create the list.)
The repl.it database is basically a big array with string indexes / keys. I'm sure that lists are an accepted data type since when I debugged before it printed db['list'] as ['#MYIDNUMBER'] but it still won't append my alt's.
db['list'] = [str(message.author.id)]
db['betenable'] = True
if message.content.startswith('$createaccount'):
db[str(message.author.id)+'wallet'] = 1000
db[str(message.author.id)+'ingame'] = 0
db[str(message.author.id)+'bet'] = 'No Party'
if str(message.author.id) not in db['list']:
db['list'].append(str(message.author.id))```
You're accessing db[list], using the list built-in, instead of the string, db['list'].

psychopy keyboard answer breaks down

I am trying to write an Go_nogo Task in Psychopy. Even though I managed to write a script which is working, there are still a few things that make troubles. First, I present pictures of emotional stimuli (im_n, neural; im_a, emotional) and people should only answer by pressing "space" if neutral emotional pictures are presented. When I run the code below everything works well until I don't press any key or the wrong key. So my question is, how do I have to write the code that I don't get kicked out of the run while not answering...? Thanks everybody!
for im in imlist: # Loop for each Image in the List
picShown = bitmap.setImage(im)
bitmap.draw()
win.flip()
rt_clock.reset()
resp = False
while rt_clock.getTime() < timelimit: # timelimit is defined 2 s
if not resp:
resp = event.getKeys(keyList=['space'])
rt = rt_clock.getTime()
if im in im_n: # im_n is an extra list of one kind of images
correctResp = 'space'
if resp[0]==correctResp:
corrFb.draw() # is defined as a "green O"
else:
incorrFb.draw() # is defined as a "red X"
win.flip()
core.wait(ISI)
I get the error message:
if resp[0]==correctResp:
IndexError: list index out of range
My guess is that you get this error message at the if resp[0]==correctResp: line:
IndexError: list index out of range
Is that true? If yes, it is simply because event.getKeys() returns an empty list [] if no responses were collected. And doing [][0] will give you the above error because there's no first element (index zero) just like [1,2,3,4][1000] will give you the same error. Note that even if you press a lot of keys and none of them are in the keyList, getKeys will return an empty list because it ignores everything but the contents of the keyList (unless you set keyList=None, in which case it accepts all keys).
There's a few simple ways out of this. Firstly, you can simply check whether resp is empty and give a "fail" score if it is and only check for correctness if it is not. A more general solution, which would work with many response keys and scoring criteria, is to do if correctResp in resp and then score as a success if yes. This comparison will work with an empty list as well, in which case it always returns False as empty lists per definition can't contain anything.
But in your particular case, you only have one response option so it is even simpler! Since you've "filtered" responses sing the keyList, you KNOW that if resp is [], the subject answered "no-go" and conversely if resp is not [], he/she answered "go". So:
if im in im_n: # im_n is an extra list of one kind of images
if resp: # if subject answered 'go'
corrFb.draw() # is defined as a "green O"
else:
incorrFb.draw() # is defined as a "red X"
Actually, I suspect that you also want to give feedback in trials without neutral images. In that case, define correct as bool(resp) is (im in im_n):
if bool(resp) is (im in im_n): # if answer correspond to trial type
corrFb.draw() # is defined as a "green O"
else:
incorrFb.draw() # is defined as a "red X"

Renaming fails for duplicated objects

I am making a renaming script, but I am getting in a bit of trouble with my
Seach and Replace function.
Actually, the function works as long as there are no duplication of the same
object in the hierarchy. For example, as depicted in the attachment, locator1
and locator2 are created from scratch, whereas locator3 is a duplication from
locator2
If I were to display them in their short name, it is as follows:
locator1
locator2
locator2|locator3
So as mentioned, when I tried to replace the word 'locator' to 'Point', the
renaming works for locator 1 and 2, but when it comes to locator3, I got the
error RuntimeError: No object matches name
As such, I was wondering if there is a better way for me to recode, cause in
cases like in Modelling, where artists duplicates the object over and over again
or using of instances..
I know that this fails is due to the short name in itself but is it possible to bypass it?
def searchReplace(self):
wordSearch = str(self.searchTxt.text())
wordReplace = str(self.replaceTxt.text())
objCnt = cmds.ls(sl=True, sn=True)
if len(objCnt) == 0:
self.searchTxt.clear()
self.replaceTxt.clear()
cmds.warning('Nothing is selected')
else:
for wordString in sorted(objCnt):
if wordSearch in wordString:
newWordString = wordString.replace(wordSearch, wordReplace)
cmds.rename(wordString, newWordString)
self.searchTxt.clear()
self.replaceTxt.clear()
print '%s' %wordString + " has changed to : " + "%s" %newWordString
This is a tricky problem, but the solution is actually really simple!
When you sort objCnt, you're doing it lexicographically:
for wordString in sorted(objCnt):
This means that locator2 comes before locator2|locator3. On its own that should be fine, but...
When locator2 is renamed, the path to locator3 has also changed, so accessing it fails.
The trick is to reverse the sort so longer objects come first. That way the children always get renamed before their parents
for wordString in sorted(objCnt, reverse=True):
For this to work, you also need to make sure your ls gives you long names, be adding the long=True argument

Categories

Resources