-1

I have this list:

list_users= [[{'points': 9, 'values': 1, 'division': 1, 'user_id': 3}], [{'points': 3, 'values': 0, 'division': 1, 'user_id': 1}], [{'points': 2, 'values': 0, 'division': 1, 'user_id': 4}], [{'points': 9, 'values': 0, 'division': 1, 'user_id': 11}], [{'points': 3, 'values': 0, 'division': 1, 'user_id': 10}], [{'points': 100, 'values': 4, 'division': 1, 'user_id': 2}], [{'points': 77, 'values': 2, 'division': 1, 'user_id': 5}], [{'points': 88, 'values': 3, 'division': 1, 'user_id': 6}], [{'points': 66, 'values': 1, 'division': 1, 'user_id': 7}], [{'points': 2, 'values': 0, 'division': 1, 'user_id': 8}]]

I need to sort the list by points and values.

How can I sort it if dict is inside a list inside the main list?

I generated this list by query and than just append to list_users?

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
62009030
  • 347
  • 1
  • 5
  • 20
  • 1
    Possible duplicate of [What arguments does Python sort function have?](http://stackoverflow.com/questions/1972672/what-arguments-does-python-sort-function-have) – Wayne Werner Jul 19 '16 at 11:48
  • 1
    You should _seriously_ consider rewriting the code that builds that list so that it produces a simple list of dicts. Having each of those dicts inside a one-element list is pointless. – PM 2Ring Jul 19 '16 at 11:52

2 Answers2

3

Access the dictionary containing points and values by indexing on the inner list:

list_users_sorted = sorted(list_users, key=lambda x: (x[0]['points'], x[0]['values']))
#                                                       ^               ^
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Is is possible to add a new field inside each position in dictionary? – 62009030 Jul 19 '16 at 11:56
  • In each dict add 'position': (number of position when is sorted) – 62009030 Jul 19 '16 at 11:57
  • Yes it is possible. Iterate through the sorted list using `enumerate` and for the dictionary in each sublist, add a new key as `'position'` and the value as the index value from `enumerate`. – Moses Koledoye Jul 19 '16 at 12:04
2

Sort using a key function for sorted that builds a tuple of points and values for each dict in each list.

def kf(x):
    return (x[0]["points"], x[0]["values"])
s = sorted(list_users, key=kf)
print(s)

Output:

[[{'division': 1, 'points': 2, 'user_id': 4, 'values': 0}],
 [{'division': 1, 'points': 2, 'user_id': 8, 'values': 0}],
 [{'division': 1, 'points': 3, 'user_id': 1, 'values': 0}],
 [{'division': 1, 'points': 3, 'user_id': 10, 'values': 0}],
 [{'division': 1, 'points': 9, 'user_id': 11, 'values': 0}],
 [{'division': 1, 'points': 9, 'user_id': 3, 'values': 1}],
 [{'division': 1, 'points': 66, 'user_id': 7, 'values': 1}],
 [{'division': 1, 'points': 77, 'user_id': 5, 'values': 2}],
 [{'division': 1, 'points': 88, 'user_id': 6, 'values': 3}],
 [{'division': 1, 'points': 100, 'user_id': 2, 'values': 4}]]