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

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

Vaibhav Vaibhav Apr-14, 2022 Dec-31, 2021 Python Python Array Python Error

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.

LinkedIn GitHub

Related Article - Python Array

  • Initiate 2-D Array in Python
  • Count the Occurrences of an Item in a One-Dimensional Array in Python
  • Python Downsample Array
  • Sort 2D Array in Python
  • Create a BitArray in Python
  • Related Article - Python Error

  • Python PermissionError: [WinError 5] Access Is Denied
  • Python TypeError: 'DataFrame' Object Is Not Callable
  • Python TypeError: Can't Convert 'List' Object to STR
  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10