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.
CodePudding user response:
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:
- Instead of return, declare a list ids = []at the beginning of the function and every time john is found you add the id to the results list, ids.append(students[id]). Finally after the loop just return ids list, or if len(ids) is 0 just return None for error management.
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