Kevin M
Kevin M

Reputation: 61

How do I get the key from dictionary of numpy.array() in python

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?

Upvotes: 1

Views: 2528

Answers (1)

python_user
python_user

Reputation: 7113

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

Upvotes: 1

Related Questions