2

I have the following kind of dictionary

import operator
my_dict = {'a':np.array((1,2)),'b':np.array((3,4))}

and I need to sorted based on the 1st column of the arrays. I can sort this other dictionary

my_dict2 = {'a':np.array((1)),'b':np.array((3))}

using

sorted(my_dict2.items(), key=operator.itemgetter(1),reverse=True)

but trying the same approach with my_dict, i.e.

sorted(my_dict.items(), key=operator.itemgetter(1),reverse=True)

throws the error message

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have tried to play with the argument in itemgetter, but I cannot order my_dict.

user1571823
  • 394
  • 5
  • 20
  • Possible duplicate of [How to sort a Python dictionary by value?](https://stackoverflow.com/questions/11932729/how-to-sort-a-python-dictionary-by-value) – Florian H Jan 24 '19 at 15:40
  • Possible duplicate of [Sorting arrays in NumPy by column](https://stackoverflow.com/questions/2828059/sorting-arrays-in-numpy-by-column) – arghtype Jan 24 '19 at 19:09

1 Answers1

0

I'm not exactly sure how to use operator to get subscripted values. So what I did was this:

sorted(my_dict.items(), key=lambda x: x[1][0],reverse=True)

Explanation:
x[1][0] means you are taking the 1 and 3 out of (1,2) and (3,4).
x[1][1] means you are taking the 2 and 4 out of (1,2) and (3,4).
x[0] is the same as itemgetter(0) which will sort by a and b, which is the keys of your dictionary.

ycx
  • 3,155
  • 3
  • 14
  • 26