0

I have a list a containing rows (also lists) with three elements each. I want to sort those according to the values in a list b in ascending order. I tried the following:

a = [[1,2,3],['hi','foo','fi'],[7,8,9]]
print(a)
b = [0.3,3,0.6]

keydict = dict(zip(a,b))
a.sort(key=keydict.get)

However im getting the error:

TypeError: unhashable type: 'list'

in the line with keydict = dict(zip(a,b)).

I expect to get this:

a = [[1,2,3],[7,8,9],['hi','foo','fi']]

What could i do to make it right?

Sebastian Dengler
  • 1,258
  • 13
  • 30

2 Answers2

3

A comprehension with sorted and a custom key is the solution:

>>> [x for _, x in sorted(enumerate(a), key=lambda x: b[x[0]])]
[[1, 2, 3], [7, 8, 9], ['hi', 'foo', 'fi']]

Or using zip:

>>> [x for _, x in sorted(zip(b, a))]
[[1, 2, 3], [7, 8, 9], ['hi', 'foo', 'fi']]
Netwave
  • 40,134
  • 6
  • 50
  • 93
1

Here's one way using sorted with a key to get the indices that would sort b and use it to sort a using a list comprehension:

[a[i] for i in sorted(range(len(b)), key=b.__getitem__)]
# [[1, 2, 3], [7, 8, 9], ['hi', 'foo', 'fi']]
yatu
  • 86,083
  • 12
  • 84
  • 139