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?

ga97dil
  • 1,139
  • 9
  • 26

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
  • 36,219
  • 6
  • 36
  • 71
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
  • 80,714
  • 11
  • 64
  • 111