Reputation: 71
I can't seem to understand why is the following returning only the first result? when there are multiple students with that same name and I'm clearly looping through the dictionary. Any thoughts?
students = {
1: {
"name": "John",
"age": 18,
"hobbies": ["Programming", "Swimming", "working out"]
},
2: {
"name": "John",
"lol": "random",
"age": 18,
"hobbies": ["Programming, swimming, working out"]
},
3: {
"name": "Bob",
"age": 18,
"hobbies": ["Programming", "Swimming", "working out"]
},
}
@app.get("/get-student")
async def get_student_by_name(name : str):
for id in students:
if students[id]["name"] == name:
return students[id]
return {"Data": "Student not found"}
The returned result is always the first one in the dictionary.
Upvotes: 0
Views: 261
Reputation: 74
This won't work since you're using 'return' statement inside the loop, if for example you are looking for 'john' the first time this parameter is found return is executed and function ends. You could for example save those values and return them all, let me show you:
Code example:
@app.get("/get-student")
async def get_student_by_name(name : str):
ids = []
for id in students:
if students[id]["name"] == name:
ids.append(students[id])
if len(ids) is 0:
return {"Data": "Student not found"}
else:
return ids
Upvotes: 3