In my python project, I have a variable called "Dictionary" that is a dictionary of various string keys with integer values.
I also have a variable that is a list containing lots and lots of strings.
I would like my code to compare the strings in the list with the keys in the dictionary and, if one matches, assign the value of said key to a variable.
Extra Information : The input here is a variable called listforwiki
which is a list of names formatted like so:
['content','content','content',]
and so on for approx 300 strings.
This then runs through a Wikipedia API query, getting a synopsis of the bio for each string, and assigning this to temp
.
This temp
string is then split into a list of multiple strings by .split()
and assigned to the variable tempstring
The expected output is the value from the dictionary. This is an integer.
All I want the code to do is compare the strings in the list tempstring
with the values in the dictionary and, if there is a match, assign the complimentary key of said value in the dictionary to the variable label
Hope that clears everything up. Below, is the code I have so far.
try:
for i in listforwiki:
temp = wikipedia.summary(i)
tempstring = temp.split()
if tempstring in dictionary:
label = dictionary[str(tempstring)]
except:
pass
it simply DOES NOT WORK
I have no clue how to fix this, so if anyone could help I'd be really grateful.
NB, the label
variable is going to be assigned to an object parameter where it will need to be an integer, I'm only making it a string currently as the next line of code under label = dictionary[str(tempstring)]
was print(label)
, purely for troubleshooting purposes.
The function split() returns an array of string as you can see here https://docs.python.org/3.3/library/stdtypes.html?highlight=split#str.split so actually tempstring
is a list of strings. What you should do is to iterate over tempstring
and check if each string is in dictionary
.
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.