-1

I have list of dictionaries in a list and need to sort the list by points-key.

I was able to sort using the first position of the 'points' list, but would like to sort based on the first position and the second position.

a = [
    {
    'label':'a',
    'points': [[70,2],[60,4]]
    }
    ,
    {
    'label':'b',
    'points': [[90,6],[80,8]]
    }
    ,
    {
    'label':'c',
    'points': [[50,10],[40,12]]
    }

]

def sort_point_by_first_occur(item):
    print item['points'][0][0]
    return item['points'][0][0]

print sorted(a, key=sort_point_by_first_occur)

current output:-

[{'points': [[50, 10], [60, 4]], 'label': 'a'}, {'points': [[50, 2], [40, 12]], 'label': 'c'}, {'points': [[90, 6], [80, 8]], 'label': 'b'}]

Excepted output:

[{'points': [[50, 2], [60, 4]], 'label': 'a'}, {'points': [[50, 10], [40, 12]], 'label': 'c'}, {'points': [[90, 6], [80, 8]], 'label': 'b'}]
user1050619
  • 19,822
  • 85
  • 237
  • 413

1 Answers1

0

I would suggest weighting to 2 values

def sort_point_by_first_occur(item):
    weighted = item['points'][0][0]*1000 + item['points'][0][1]
    return weighted

This way, if the first position is equal, the second one would be a tie breaker

Uri Goren
  • 13,386
  • 6
  • 58
  • 110