0

I am converting a Python dictionary to NumPy array.

import numpy as np

myDict = {
        1: "AAA",
        2: "BBB",
        3: "CCC",
        4: "AAA",
        5: "BBB"
        }

myNumPyArray = np.asarray(myDict, dtype=dict, order="C")

print(myNumPyArray) 

Output

{1: 'AAA', 2: 'BBB', 3: 'CCC', 4: 'AAA', 5: 'BBB'}

Why is it showing the dictionary in the output?

user366312
  • 16,949
  • 65
  • 235
  • 452
  • You could do `myNumPyArray = np.array(list(myDict.items()))` instead. – Ari Cooper-Davis Jul 18 '19 at 08:30
  • Try printing the `repr(myNumPyArray)`. – Mateen Ulhaq Jul 18 '19 at 08:31
  • Possible duplicate of [python dict to numpy structured array](https://stackoverflow.com/questions/15579649/python-dict-to-numpy-structured-array) – Paritosh Singh Jul 18 '19 at 08:31
  • `print(repr(myNumpyArray))` outputs: `array({1: 'AAA', 2: 'BBB'}, dtype=object)`, so there's nothing wrong – ForceBru Jul 18 '19 at 08:32
  • 3
    the issue is, it's an array of a dict. Numpy cannot know how you want the dict to be inferred, also take a look at [docs](https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html). Use `.items.()` or `.values()` on the dict before calling numpy array on it – Paritosh Singh Jul 18 '19 at 08:32
  • 1
    What output do you expect? [The manual says](https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html) you should pass "lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays" for the first argument. – Leporello Jul 18 '19 at 08:32

1 Answers1

1

This "fails" because an array containing a single scalar value of type 'object' is created. This scalar value will be a pointer to the dictionary. If you want to transform content of the dictionary to ndarray you can use structured array with 2 fields. One for integer index, other for value as a fixed length string. Using np.fromiter is a fast method because it avoids creation of any temporary objects.

np.fromiter(myDict.items(), dtype='i4,U3', count=len(myDict))
tstanisl
  • 13,520
  • 2
  • 25
  • 40