Others have asked similar questions, but the answers haven't helped me. I'm a beginner working through a tutorial and struggling with this last step.
I have a list of neighbors and have created a function (called distance_all()
) that, for a given neighbor, will return a list containing how far away each of the other neighbors are from the given neighbor. Now I'm trying to write a function that orders the list from nearest to furthest neighbor, and I can't get it to work. I also need the function to take an optional third argument that specifies how many neighbors are returned.
Here's the original list of neighbors:
neighbors = [{'name': 'Fred', 'avenue': 4, 'street': 8},
{'name': 'Suzie', 'avenue': 1, 'street': 11},
{'name': 'Bob', 'avenue': 5, 'street': 8},
{'name': 'Edgar', 'avenue': 6, 'street': 13},
{'name': 'Steven', 'avenue': 3, 'street': 6},
{'name': 'Natalie', 'avenue': 5, 'street': 4}]
When I run the function that calculates distance, I get the following:
#input
distance_all(fred, neighbors)
#output
[{'name': 'Suzie', 'avenue': 1, 'street': 11, 'distance': 4.242640687119285},
{'name': 'Bob', 'avenue': 5, 'street': 8, 'distance': 1.0},
{'name': 'Edgar', 'avenue': 6, 'street': 13, 'distance': 5.385164807134504},
{'name': 'Steven', 'avenue': 3, 'street': 6, 'distance': 2.23606797749979},
{'name': 'Natalie', 'avenue': 5, 'street': 4, 'distance': 4.123105625617661}]
Now I'm trying to write a function that (1) runs the distance_all()
function, (2) orders the output list from nearest to furthest, and (3) has an optional third argument that specifies how many neighbors to include in the output list. I haven't gotten to this third step yet because I'm struggling with the second, but any help is appreciated. I've tried a number of things, but here is my most recent attempt:
def nearest_neighbors(first_neighbor, neighbors, number = None):
neighbor_distance = [distance_all(first_neighbor, neighbors)]
return (sorted(neighbor_distance, key = lambda i: i['distance']))
When I run nearest_neighbors(fred, neighbors, 2)
I get the error TypeError: list indices must be integers or slices, not str
. I don't know what I'm doing wrong. Thanks for your help.