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.
-
Possible duplicate of How to sort a Python dictionary by value?Florian H– Florian H2019年01月24日 15:40:00 +00:00Commented Jan 24, 2019 at 15:40
-
Possible duplicate of Sorting arrays in NumPy by columnarghtype– arghtype2019年01月24日 19:09:44 +00:00Commented Jan 24, 2019 at 19:09
1 Answer 1
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.