ctfd
ctfd

Reputation: 348

Comparing nested array to dictionary values

I have an array that looks like this:

[[ 36 119]
 [ 36 148]
 [ 36 179]
 [ 67 209]
 [ 69  84]
 [ 96 240]]

and a dictionary like this:

{84: [36, 119], 85: [36, 148], 86: [36, 160]}

I would like to check if any of the values of the array are present in the dictionary, then return the numbers. So for the example above it should return 84, 85. I tried to compare using:

pairs = zip(array, dict)
print(any(x != y for x, y in pairs))

Although I get an error:

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

Upvotes: 0

Views: 40

Answers (2)

Tristan Nemoz
Tristan Nemoz

Reputation: 2048

Something like this?

>>> my_dict = {84: [36, 119], 85: [36, 148], 86: [36, 160]}
>>> x = np.array([[ 36, 119], [ 36, 148], [ 36, 179], [ 67, 209], [ 69 ,84],[96,240]])
>>> [keys for (keys, value) in my_dict.items() if (x == value).all(axis=1).any()]
[84, 85]

Upvotes: 1

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can use np.isin and np.ndarray.all:

>>> pairs = {84: [36, 119], 85: [36, 148], 86: [36, 160]}
>>> array 
array([[ 36, 119],
       [ 36, 148],
       [ 36, 179],
       [ 67, 209],
       [ 69,  84],
       [ 96, 240]])

>>> [k for k, v in pairs.items() if np.isin(v, array).all()]
[84, 85]

Upvotes: 2

Related Questions