1

I have a dictionary that has numpy.array() as a values:

dictionary = {0: array([11,  0,  2,  0]), 1: array([  2,   0,   1, 100]), 1: array([  5,   10,   1, 100])}

I want to get key of specific value, e.g: [11, 0, 2, 0]. So, I wrote this code:

print(list(a_dictionary.keys())[list(a_dictionary.values()).index([11,  0,  2,  0])]) 

But it gives me an error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How to handle this? Is there any other way to get a key of specific list value in dictionary?

1 Answer 1

1

You can use np.array_equal to check if two numpy arrays are equal. The following code will set key_needed to the key in dictionary if the elements match, if there is no value with that numpy array key_needed will be None.

If there are multiple keys that have the same numpy array this will return only the first occurrence.

import numpy as np

d={0: np.array([11,  0,  2,  0]), 1: np.array([  2,   0,   1, 100]), 1: np.array([  5,   10,   1, 100])}

value_to_search=[11, 0, 2, 0]

value_to_search=np.array(value_to_search)

key_needed=None

for key in d:
    if np.array_equal(d[key],value_to_search):
        key_needed=key
        break

print(key_needed) # 0
Sign up to request clarification or add additional context in comments.

1 Comment

np :), if you want a one liner version where the array values can be in multiple keys you can try this key_needed=[k for k,v in d.items() if np.array_equal(v,value_to_search)]. An empty list [] if no values are present and a list that has the keys if the keys are duplicate.

Your Answer

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.