I have the following code:
lower_threshold = 6.33
upper_threshold = 1e+30
threshold_dict_by_patient_and_visit = {
"k2-01-003|15" : [15.007, 1e+30]
}
mylist = ['k2-01-003|18', 'k2-01-003|13','k2-01-003|15']
for i in range(3):
for patient_visit in mylist:
if (patient_visit in threshold_dict_by_patient_and_visit):
lower_threshold, upper_threshold = threshold_dict_by_patient_and_visit[patient_visit]
print(i, patient_visit, lower_threshold, upper_threshold)
The task I want to achieve is this:
- Within the
range(3)loop, loop throughmylist. - When the content of my list exist in
threshold_dict_by_patient_and_visitdictionary (in this casek2-01-003|15) replace thelower_thresholdandupper_thresholdwith the value in that dictionary. Otherwise use default value:6.33and1e+30
The result I expect is this:
0 k2-01-003|18 6.33 1e+30
0 k2-01-003|13 6.33 1e+30
0 k2-01-003|15 15.007 1e+30
1 k2-01-003|18 6.33 1e+30
1 k2-01-003|13 6.33 1e+30
1 k2-01-003|15 15.007 1e+30
2 k2-01-003|18 6.33 1e+30
2 k2-01-003|13 6.33 1e+30
2 k2-01-003|15 15.007 1e+30
Why it gives this instead:
0 k2-01-003|18 6.33 1e+30
0 k2-01-003|13 6.33 1e+30
0 k2-01-003|15 15.007 1e+30
1 k2-01-003|18 15.007 1e+30
1 k2-01-003|13 15.007 1e+30
1 k2-01-003|15 15.007 1e+30
2 k2-01-003|18 15.007 1e+30
2 k2-01-003|13 15.007 1e+30
2 k2-01-003|15 15.007 1e+30
What's the right way to go about it?
I'm using Python 3.8.5.
Update
I tried to add else but still doesn't work:
for i in range(3):
for patient_visit in mylist:
if (patient_visit in threshold_dict_by_patient_and_visit):
lower_threshold, upper_threshold = threshold_dict_by_patient_and_visit[patient_visit]
else:
lower_threshold, upper_threshold = lower_threshold, upper_threshold
print(i, patient_visit, lower_threshold, upper_threshold)
elsewhere you reset to the default values for the threshold variables?lower_threshold, upper_threshold = lower_threshold, upper_thresholdyou just assign the same values as the variables already have. You need to assign the default value, explicitly.