Python beginner here. I am having a problem when attempting to search for a string within a dictionary.
The program I am writing is using xlrd to match data from a excel spreadsheet (S2name) with a dictionary key, to then return the value assigned to the key. This is for the purpose of matching quality control tests with chemical data.
The dictionary is much like this:
dQC = {'4266152-001': 'METHOD_BLANK',
'4266152-002': 'LCS',
'4266152-004': 'LAB_DUPLICATE',
etc..
My code is working, except for the fact that the search function is returning the wrong result from the dictionary.
I have isolated the problem to the v variable in the following:
S2name = (sheet2.cell_value(row_index, 0))
for key, value in dQC.items():
def search(dic, lookup):
for v in key:
print("This should be the key in dQC, not the number %s" % v)
if v in lookup:
return v # I would obviously return value here, but it returns the wrong one.
else:
return False
QCtype = (search(dQC, S2name))
print(QCtype)
Result:
This should be the key in dQC, not the number 4
4
For some reason, v is searching for only the first digit in the string (ie: 4) and not the whole string (ie: 4266152-001), so when I call the value using QCtype, it returns the wrong one. I would like v to use the first 10 characters when iterating the search, not he first.
Note, in the script, I am returning v just to check it. I would otherwise be returning value.
EDIT:
Perhaps it is clearer if I link to the thread that I used some of the code from.
I was under the assumption that this would search for the entire word in the dictionary key, not for the individual letters in key, which makes sense to me now.
How to search if dictionary value contains certain string with Python