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.

asked Jan 24, 2019 at 15:33
2

1 Answer 1

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.

answered Jan 24, 2019 at 15:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.