📜  如何将字典转换为 NumPy 数组?

📅  最后修改于: 2022-05-13 01:55:42.108000             🧑  作者: Mango

如何将字典转换为 NumPy 数组?

有时需要将Python中的字典转换为 NumPy 数组, Python提供了一种有效的方法来执行此操作。将字典转换为 NumPy 数组会生成一个数组,其中包含字典中的键值对。 Python提供numpy.array()方法将字典转换为 NumPy 数组,但在应用此方法之前,我们必须做一些前置任务。作为前置任务,请遵循这个简单的三个步骤

  1. 首先打电话 dict.items()返回字典中的一组键值对。
  2. 然后使用list(obj)将此组作为对象将其转换为列表。
  3. 最后,将此列表作为数据调用numpy.array(data)以将其转换为数组。

示例 1:

Python
# Python program to convert
# dictionary to numpy array
  
# Import required package
import numpy as np
  
# Creating a Dictionary
# with Integer Keys
dict = {1: 'Geeks',
        2: 'For',
        3: 'Geeks'}
  
# to return a group of the key-value
# pairs in the dictionary
result = dict.items()
  
# Convert object to a list
data = list(result)
  
# Convert list to an array
numpyArray = np.array(data)
  
# print the numpy array
print(numpyArray)


Python
# Python program to convert
# dictionary to numpy array
  
# Import required package
import numpy as np
  
# Creating a Nested Dictionary
dict = {1: 'Geeks',
        2: 'For',
        3: {'A': 'Welcome',
            'B': 'To',
            'C': 'Geeks'}
        }
  
# to return a group of the key-value
# pairs in the dictionary
result = dict.items()
  
# Convert object to a list
data = list(result)
  
# Convert list to an array
numpyArray = np.array(data)
  
# print the numpy array
print(numpyArray)


Python
# Python program to convert
# dictionary to numpy array
  
# Import required package
import numpy as np
  
# Creating a Dictionary
# with Mixed keys
dict = {'Name': 'Geeks',
        1: [1, 2, 3, 4]}
  
# to return a group of the key-value
# pairs in the dictionary
result = dict.items()
  
# Convert object to a list
data = list(result)
  
# Convert list to an array
numpyArray = np.array(data)
  
# print the numpy array
print(numpyArray)


输出:

[['1' 'Geeks']
 ['2' 'For']
 ['3' 'Geeks']]

示例 2:

Python

# Python program to convert
# dictionary to numpy array
  
# Import required package
import numpy as np
  
# Creating a Nested Dictionary
dict = {1: 'Geeks',
        2: 'For',
        3: {'A': 'Welcome',
            'B': 'To',
            'C': 'Geeks'}
        }
  
# to return a group of the key-value
# pairs in the dictionary
result = dict.items()
  
# Convert object to a list
data = list(result)
  
# Convert list to an array
numpyArray = np.array(data)
  
# print the numpy array
print(numpyArray)

输出:

[[1 'Geeks']
 [2 'For']
 [3 {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}]]

示例 3:

Python

# Python program to convert
# dictionary to numpy array
  
# Import required package
import numpy as np
  
# Creating a Dictionary
# with Mixed keys
dict = {'Name': 'Geeks',
        1: [1, 2, 3, 4]}
  
# to return a group of the key-value
# pairs in the dictionary
result = dict.items()
  
# Convert object to a list
data = list(result)
  
# Convert list to an array
numpyArray = np.array(data)
  
# print the numpy array
print(numpyArray)

输出:

[['Name' 'Geeks']
 [1 list([1, 2, 3, 4])]]