Vladislav Ladenkov Vladislav Ladenkov - 1 month ago 4x
Python Question

Searching an element in a list of double-nested dictionaries with generator

I have a list of dictionaris. In every dictionary, i need to use values, which are in the dictionaries, which are in the dictionaries:

[{'Cells': {'Address': 'Нижний Кисельный переулок, дом 3, строение 1',
'AdmArea': 'Центральный административный округ',
'District': 'Мещанский район',
'IsNetObject': 'нет',
'Name': 'Юнион Джек',
'OperatingCompany': None,
'PublicPhone': [{'PublicPhone': '(495) 621-19-63'}],
'SeatsCount': 30,
'SocialPrivileges': 'нет',
'geoData': {'coordinates': [37.62158794615201, 55.76536695660836],
'type': 'Point'},
'global_id': 20660594},
'Id': 'ae3e9479-070f-4d66-9429-de3acd8427ac',
'Number': 1},
{'Cells': {'Address': 'проспект Мира, дом 91, корпус 1',
'AdmArea': 'Северо-Восточный административный округ',
'District': 'Останкинский район',
'IsNetObject': 'нет',
'Name': 'Бар «Джонни Грин Паб»',
'OperatingCompany': None,
'PublicPhone': [{'PublicPhone': '(495) 602-45-85'}],
'SeatsCount': 50,
'SocialPrivileges': 'нет',
'geoData': {'coordinates': [37.635709999611, 55.805575000159],
'type': 'Point'},
'global_id': 20660628},
'Id': 'c5301186-00bb-4a1f-af03-6f3237292a51',
'Number': 2},

I'm given coordinates
[lattitude, attitude]
. I want to find the smallest distance between given coordinates and coordinates in dictionaries. So i need to iterate over dictionaries and calculate the distance.
I'am quite new, but i want to be more proffesional with using a generator to find the distance. But, using
, will stop iterating as soon as it meets the condition, so i'am just dont if it is possible.

So, to be short: What is the most efficient way to find the smallest distance from a given spot in this data structure?


First, let's assume you have a function get_distance() which finds distance between two points with lat and long. I can describe it, but I think for now it is not the point of the question. Then, the code will be look like:

cells = {...} # your data is here
point = [..] # coordinates of the point 
distances = {get_distance(point, cell['Cells']['geoData']['coordinates']): cell['Id'] for cell in cells}  # I don't know do you need a whole entry to be found or only `Id`
closest_id = distances[min(distances.keys())]

Off course it is only of possible solutions. I've made it with dict comprehension but sometimes it is more easy to rea to do it with suaul for loop. Please let me know if something is unclear.

If you also have problems with writing get_distance function - here is an one of examples: How can I quickly estimate the distance between two (latitude, longitude) points? (of course it needs to be modified a bit to look like get_distance function)