如何在Python中将字典转换为矩阵或nArray?


在本文中,我们将向您展示如何使用Python中NumPy库的array()函数将字典转换为矩阵或NumPy数组。

有时需要将Python中的字典转换为NumPy数组,Python提供了一种高效的方法来做到这一点。将字典转换为NumPy数组会生成一个包含字典中键值对的数组。

在本节中,我们将研究在Python中将各种类型的字典转换为NumPy数组的示例。

  • 将字典转换为NumPy数组
  • 将嵌套字典转换为NumPy数组
  • 将具有混合键的字典转换为NumPy数组

numpy.array() 函数

它返回一个ndarray。ndarray是一个满足给定要求的数组对象。

要将字典转换为NumPy数组,Python具有numpy.array()方法,但我们必须首先进行一些预处理工作。请按照这三个基本步骤作为预处理任务。

  • 首先,使用dict.items()获取字典中键值对的集合。
  • 然后,将此集合作为对象,使用list(obj)将其转换为列表。
  • 最后,使用此列表作为数据,调用numpy.array(data)将其转换为数组。

语法

numpy.array(object, dtype = None, *, copy = True, order = ‘K’, subok = False, ndmin = 0)

参数

  • object − 这是一个数组或任何公开数组接口的对象。

  • dtype − 数组的首选数据类型。

  • copy − 如果为真(默认值),则复制项目。否则,只有当__array__返回副本时才会生成副本。

  • order − 它表示数组的内存布局。

  • subok − 如果为真,则子类将被传递;否则,返回的数组将强制为基类数组(默认值)。

  • ndmin − 指示结果数组的最小维度数。

  • 返回值 − 返回一个ndarray(这是一个满足指定要求的数组对象)。

将字典转换为NumPy数组

算法(步骤)

以下是执行所需任务的算法/步骤:

  • 使用import关键字,导入numpy模块,并使用别名(np)。

  • 创建一个变量来存储输入字典。

  • 对输入字典应用items()函数(返回字典中键值对的集合),以获取字典中的所有键值对,并创建一个变量来存储它。

  • 使用list()函数(返回可迭代对象的列表),将字典的所有键值对转换为列表数据类型。

  • 使用NumPy模块的array()函数(返回一个ndarray。ndarray是一个满足给定要求的数组对象)将上述数据列表转换为NumPy数组。

  • 转换后,打印输入字典的结果NumPy数组。

示例

以下程序使用array()函数将输入字典转换为NumPy数组并返回它:

Open Compiler
# importing numpy module with an alias name import numpy as np # creating a dictionary inputDict = {1: 'Hello', 2: 'Tutorialspoint', 3: 'python'} # getting all the key-value pairs in the dictionary result_keyvalpairs = inputDict.items() # converting an object to a list list_data = list(result_keyvalpairs) # converting list to an numpy array using numpy array() function numpy_array = np.array(list_data) print("Input Dictionary =",inputDict) # printing the resultant numpy array print("The resultant numpy array:\n", numpy_array)

输出

执行上述程序后,将生成以下输出:

Input Dictionary = {1: 'Hello', 2: 'Tutorialspoint', 3: 'python'}
The resultant numpy array:
 [['1' 'Hello']
 ['2' 'Tutorialspoint']
 ['3' 'python']]

将嵌套字典转换为NumPy数组

算法(步骤)

以下是执行所需任务的算法/步骤:

  • 创建一个变量来存储输入嵌套字典(字典在另一个字典中)。

  • 使用list()函数(返回可迭代对象的列表),将字典的所有嵌套键值对转换为列表数据类型。

  • 使用NumPy模块的array()函数将上述数据列表转换为NumPy数组。

  • 转换后,打印输入字典的结果NumPy数组。

示例

以下程序使用array()函数将嵌套输入字典转换为NumPy数组并返回它:

Open Compiler
# importing NumPy module with an alias name import numpy as np # creating a nested dictionary nestedDictionary = {1: 'Hello', 2: 'Tutorialspoint', 3: {'X': 'This is', 'Y': 'python', 'Z': 'code'}} # getting all the key-value pairs in the dictionary result_keyvalpairs = nestedDictionary.items() # converting an object to a list list_data = list(result_keyvalpairs) # converting list to an array using numpy array() function numpy_array = np.array(list_data) print("Input nested Dictionary = ",nestedDictionary) # printing the resultant numpy array print("\nThe resultant numpy array:\n", numpy_array)

输出

执行上述程序后,将生成以下输出:

Input nested Dictionary =  {1: 'Hello', 2: 'Tutorialspoint', 3: {'X': 'This is', 'Y': 'python', 'Z': 'code'}}

The resultant numpy array:
 [[1 'Hello']
   [2 'Tutorialspoint']
   [3 {'X': 'This is', 'Y': 'python', 'Z': 'code'}]]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

将具有混合键的字典转换为NumPy数组

创建一个具有混合键(例如字符串、整数、浮点数、列表等)的输入字典,并用随机值填充它。

示例

以下程序使用array()函数将具有混合键的字典转换为NumPy数组并返回它:

Open Compiler
# importing numpy module with an alias name import numpy as np # creating a dictionary with mixed keys(like string and numbers as keys) nestedDictionary = {'website': 'Tutorialspoint', 10: [2, 5, 8]} # getting all the key-value pairs in the dictionary result_keyvalpairs = nestedDictionary.items() # converting an object to a list list_data = list(result_keyvalpairs) # converting list to an array using numpy array() function numpy_array = np.array(list_data, dtype=object) # printing the resultant numpy array print("The resultant numpy array:\n", numpy_array)

输出

执行上述程序后,将生成以下输出:

The resultant numpy array:
 [['website' 'Tutorialspoint']
   [10 list([2, 5, 8])]]

结论

在本文中,我们学习了字典中各种类型的键值对,以及如何在Python中将它们转换为矩阵或NumPy数组。

更新于:2022年10月12日

17K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告