SmokiJ
SmokiJ

Reputation: 25

Sort list of lists containing dictionaries in Python

I am trying to implement genetic algos to optimize pathways. For that, I need to sort lists.

The basic list (list_cities) looks like this:

[[{'city': 'Pau', 'lan': 43.293295, 'lng': -0.36357}, {'city': 'Marseille', 'lan': 43.293551, 'lng': 5.377397}, {'distance': 5572.500801706894}], [{'city': 'Nice', 'lan': 43.70168, 'lng': 7.260711}, {'city': 'Lyon', 'lan': 45.759132, 'lng': 4.834604}, {'distance': 6306.2650380290725}]]

As you can see, I have a global list, containing several lists (200) containing cities themselves and a distance (representing the total distance to link all the cities in the order of the list. I would like to sort my 200 city lists, by the last value which is the distance. I tried in many ways but without success.

My last try :

sort_list = sorted(list_cities, key=lambda k: k['distance'])

Which give me the following result :

TypeError: list indices must be integers or slices, not str

Upvotes: 0

Views: 441

Answers (1)

tevemadar
tevemadar

Reputation: 13195

The [[{},{}],[{},{}]] thing is a list of lists containing objects dicts (which I keep calling objects for the rest of this answer because the data is coming from JSON anyway). So in order to sort the lists by a number contained by an inner object, you have to find the given object in the list, and then get the number from it.
As the example suggests and your comment confirms, the distance is always in the last element which you can access via index -1, and thus

sort_list = sorted(list_cities, key=lambda k: k[-1]['distance'])

could work.

About the other question: I would feel it more natural to put only the cities in a list in an object:

[
 {
  'cities':[
   {'city':'Pau','lat':...,'lon':...},
   {<2nd city>},
   ...
   {<last city>}
  ],
  'distance':...
 },
 ...
]

then it would work with the original attempt.
(Sorry about the clumsy example, I am typing it on touchscreen, uh)

Upvotes: 1

Related Questions