How to Fix the Iteration Over a 0-D Array Error in Python NumPy

Vaibhav Vaibhav Feb 02, 2024
How to Fix the Iteration Over a 0-D Array Error in Python NumPy

The error TypeError: iteration over a 0-d array occurs when iteration is performed over an iterable of 0 dimension. In this article, we will learn how to fix the TypeError: iteration over a 0-d array error in Python NumPy.

How to Fix the TypeError: iteration over a 0-d array Error Due in Python NumPy

The following Python code depicts a scenario where we can run into this error.

import numpy as np

data = {
    "AB": 1.01,
    "CD": 2.02,
    "EF": 3.03,
    "GH": 4.04,
    "IJ": 5.05,
}

keys, values = np.array(data.items()).T
print(keys)
print(values)

Output:

Traceback (most recent call last):
  File "<string>", line 11, in <module>
TypeError: iteration over a 0-d array

The reason behind this error is the data type of data.items(), which is <class 'dict_items'>. To avoid this error, we have to convert its data type to a list or a tuple. The following Python code shows how to fix this error using a list and a tuple.

Solution using a list.

import numpy as np

data = {
    "AB": 1.01,
    "CD": 2.02,
    "EF": 3.03,
    "GH": 4.04,
    "IJ": 5.05,
}
print(type(list(data.items())))
keys, values = np.array(list(data.items())).T
print(keys)
print(values)

Output:

<class 'list'>
['AB' 'CD' 'EF' 'GH' 'IJ']
['1.01' '2.02' '3.03' '4.04' '5.05']

Below is a solution using a tuple.

import numpy as np

data = {
    "AB": 1.01,
    "CD": 2.02,
    "EF": 3.03,
    "GH": 4.04,
    "IJ": 5.05,
}
print(type(tuple(data.items())))
keys, values = np.array(tuple(data.items())).T
print(keys)
print(values)

Output:

<class 'tuple'>
['AB' 'CD' 'EF' 'GH' 'IJ']
['1.01' '2.02' '3.03' '4.04' '5.05']
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python Array

Related Article - Python Error