I tried to use numpy's intersect1d to compare the keys in two dictionaries. However, this always returns an intersection of zero, for some reason related to dictionary keys being objects. I want to know why this behavior is desireable in any way.
d1 = {'a':1, 'b':2}
d2 = {'b':2, 'c':3}
np.intersect1d(d1.keys(), d2.keys())
> array([], dtype=object)
However,
np.intersect1d(list(d1.keys()), list(d2.keys()))
> array(['b'], dtype='<U1')
Is this intended behavior and if so, why?
Dictionary keys are special objects (set-like) that are dynamic views on the dictionary's keys (see doc). They do behave "unexpectedly" (for instance you can't slice them like a list:
d1.keys()[0])Now I'm not sure why (see below)
np.intersect1dis not working as expected ondict.keys(), but why use numpy here anyway? This function is defined to work on arrays, not on any object.Furthermore, since the objects would need to be converted to arrays, this is slower than pure python. Better use a simple
setintersectionset(d1) & set(d2), or even better (as suggested by @nocomment):d1.keys() & d2.keys():but why?
intersect1dtakes two array_like as input, which are defined as any scalar or sequence than can be converted to array (doc). Howevernp.array(d1.keys())creates an object array containing thekeysobject (a single object) and not the keys as items:A perhaps interesting demonstration is to see the effect of a self intersection, yielding this unique object: