Issue
Data:
import numpy as np
d = {"a": 10, "b": 11, "c":12}
print(d) # This gives {'a': 10, 'b': 11, 'c': 12}
Problem:
So we try to obtain the index of the max value in the d.values()
:
print(np.argmax(d.values()))
This gives 0, which is incorrect. The correct answer should be 2. But if we try this:
print(d.values()) # This gives dict_values([10, 11, 12])
print(np.argmax([10, 11, 12]))
This is correct
So why is this?
Thanks in advance!
Solution
Dictionary view objects are different from Lists.
Views are "pseudo-set-like", in that they don't support indexing, so what you can do with them is test for membership and iterate over them (because keys are hashable and unique, the keys and items views are more "set-like" in that they don't contain duplicates).
import numpy as np
d = {"a": 10, "b": 11, "c":12}
view_object = d.values()
Now if you try to index view_object
:
print(view_object[0])
TypeError: 'dict_values' object is not subscriptable
Unlike lists, you cannot index Dictionary view objects
Coming back to np.argmax()
:
Returns the indices of the maximum values along an axis.
https://github.com/numpy/numpy/blob/v1.26.0/numpy/core/fromnumeric.py#L1140-L1229
If the object is not subscriptable, np.argmax() will return 0.
e.g.
np.argmax({1,2,3})
0
np.argmax(d.values())
0
Answered By - Goku - stands with Palestine
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.