Python 将字典列表转换为列表字典

Python 将字典列表转换为列表字典

在Python中, 字典 是一种内置的数据结构,它以键值对的形式存储数据。它允许根据对应的键有效地检索和修改值。字典中的每个键必须是唯一的,并且与一个特定的值相关联。

列表字典 是一个字典,其中与每个键相关联的值是列表。这意味着每个键映射到多个值,并且这些值作为列表中的元素存储。

另一方面, 字典列表 是一个包含多个字典作为其元素的列表。列表中的每个字典可以具有其自己的键值对集。

在本文中,我们将学习如何在Python中将字典列表转换为列表字典。

示例

ListOfDictionaries = [
    {'cricketer': 'virat', 'score': 90},
    {'cricketer': 'chahal', 'score': 30},
    {'cricketer': 'dhoni', 'score': 120},
    {'cricketer': 'pandya', 'score': 110},
    {'cricketer': 'smith', 'score': 115}

]
DictionaryofLists: {'cricketer': ['virat', 'chahal', 'dhoni', 'pandya', 'smith'], 'score': [90, 30, 120, 110, 115]}

使用的方法

以下是完成此任务所使用的各种方法:

  • 使用for循环

  • 使用字典推导式

  • 使用pandas DataFrame

  • 使用NumPy模块

方法1:使用for循环

此方法创建一个名为dictOflists的空字典,用于存储结果字典列表。然后,它使用循环遍历输入列表中的每个字典,将’cricketer’键作为字典的键并将整个字典分配为其值。最后,它显示结果字典列表,其中每个cricketer是映射到其相应成绩字典的键。

步骤

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

  • 创建一个变量来存储输入的 字典列表

  • 创建一个空字典来存储结果字典列表。

  • 使用 for循环 遍历输入的字典列表,将输入的字典列表转换为字典列表。

  • 显示输出的字典列表。

示例

以下程序使用for循环将字典列表转换为字典列表:

# input list of dictionaries
inputListOfDicts = [
    {'cricketer': 'virat', 'scores': [40, 70, 90]},
    {'cricketer': 'chahal', 'scores': [10, 25, 30]},
    {'cricketer': 'dhoni', 'scores': [35, 65, 120]},
    {'cricketer': 'pandya', 'scores': [58, 89, 110]},
    {'cricketer': 'smith', 'scores': [76, 110, 115]}

]

# creating an empty dictionary for 
# storing resultant dictionary of lists
dictOflists = {}

# traversing in the input list of dictionaries 
# for converting input list of dictionaries to a dictionary of lists
for i in inputListOfDicts:
  # Getting values
    cricketer = i['cricketer']
    dictOflists[cricketer] = i

# displaying the output dictionary of lists
dictOflists

输出

{'virat': {'cricketer': 'virat', 'scores': [40, 70, 90]},
 'chahal': {'cricketer': 'chahal', 'scores': [10, 25, 30]},
 'dhoni': {'cricketer': 'dhoni', 'scores': [35, 65, 120]},
 'pandya': {'cricketer': 'pandya', 'scores': [58, 89, 110]},
 'smith': {'cricketer': 'smith', 'scores': [76, 110, 115]}}

方法2:使用字典理解

在Python中,字典理解是一种简洁的方法,通过迭代现有的序列或可迭代对象,应用表达式或条件生成键-值对,从而生成简洁而易读的代码。它允许在一行代码中创建字典,结合了迭代和转换的功能。

步骤

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

  • 创建一个变量来存储输入的 字典列表

  • 打印字典,其中键是输入的第一个字典中的键。

  • 使用列表理解打印每个字典中相应值的列表。

示例

以下程序使用字典理解将字典列表转换为列表字典:

# input list of dictionaries
inputListOfDicts = [
    {'cricketer': 'virat', 'score': 90},
    {'cricketer': 'chahal', 'score': 30},
    {'cricketer': 'dhoni', 'score': 120},
    {'cricketer': 'pandya', 'score': 110},
    {'cricketer': 'smith', 'score': 115}

]

# Using list comprehension
print({dict_key: [p[dict_key] for p in inputListOfDicts] for dict_key in inputListOfDicts[0]})

输出

{'cricketer': ['virat', 'chahal', 'dhoni', 'pandya', 'smith'], 'score': [90, 30, 120, 110, 115]}

方法3:使用pandas DataFrame

在这个方法中,我们将使用pandas dataframe将一个字典列表转换成一个列表字典。

语法

pandas.DataFrame(listofdictionary).to_dict(orient=”list”)

参数

  • listofdictionary: 输入的字典列表。

  • to_dict()函数: 将其转换为字典。

  • orient: 将其转换为列表。

步骤

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

  • 使用import关键字导入具有别名的pandas模块。

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

  • 将字典列表inputListOfDicts转换为pandas DataFrame,然后将DataFrame转换为字典,其中键是DataFrame的列名,值是包含每一列值的列表。

示例

下面的程序使用pandas数据帧将字典列表转换为列表字典。

# importing pandas module
import pandas as pd


# input list of dictionaries
inputListOfDicts = [
    {"cricketer": "virat", "score": 90},
    {"cricketer": "chahal", "score": 30},
    {"cricketer": "dhoni", "score": 120},
    {"cricketer": "pandya", "score": 110},
    {"cricketer": "smith", "score": 115},
]

# converting into  dictionary of lists using pandas to_dict()
pd.DataFrame(inputListOfDicts).to_dict(orient="list")

输出

On executing, the above program will generate the following output –
{'cricketer': ['virat', 'chahal', 'dhoni', 'pandya', 'smith'],
 'score': [90, 30, 120, 110, 115]}

方法4:使用NumPy模块

步骤

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

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

  • 使用array()函数创建一个numpy数组。

  • 使用索引访问数组值的第一个元素(从0开始)。

  • 使用索引作为键打印结果。

以下程序使用numpy模块将字典列表转换为列表的字典-

# importing numpy module with an alias name 
import numpy as np

# creating a numpy array using array() function 
inputArray = np.array([(25, 45), (30, 70)],
                dtype=[('num1', int),
                    ('num2', int)])


# accessing first array element using indexing
# (starts from 0)
print(inputArray[0])

# Printing by using key
print(inputArray['num1'])

输出

On executing, the above program will generate the following output –
(25, 45)
[25 30]

代码使用指定的数据类型和字段名称创建了一个NumPy数组inputArray。然后演示了使用索引和基于键的索引访问数组元素的方法。

结论

总之,本文介绍了将字典列表转换为列表字典的四种不同技术。探讨的方法包括传统的for循环迭代、简洁的字典推导、利用pandas DataFrame和应用NumPy模块。每种方法都有自己的优势和适用性,基于具体需求和可用资源选择合适的方法。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程