利用 Python 中列表内容创建字典
在 python 中频繁需要将集合类型从一种类型更改为另一种类型。本文将介绍如何利用多个给定列表创建字典。挑战在于能够合并所有这些列表,以将所有这些值组合在一个字典键值格式中。
利用 zip
zip 函数可用于合并不同列表的值,如下所示。在下面的示例中,我们接受了三个列表作为输入,并将它们组合形成一个字典。其中一个列表提供字典的键,而其他两个列表则保存对应于每个键的值字段。
示例
key_list = [1, 2,3]
day_list = ['Friday', 'Saturday','Sunday']
fruit_list = ['Apple','Banana','Grape']
# Given Lists
print("Given key list : " + str(key_list))
print("Given day list : " + str(day_list))
print("Given fruit list : " + str(fruit_list))
# Dictionary creation
res = {key: {'Day': day, 'Fruit': fruit} for key, day, fruit in
zip(key_list, day_list, fruit_list)}
# Result
print("The final dictionary : \n" ,res)输出
运行以上代码将获得以下结果 -
Given key list : [1, 2, 3]
Given day list : ['Friday', 'Saturday', 'Sunday']
Given fruit list : ['Apple', 'Banana', 'Grape']
The final dictionary :
{1: {'Day': 'Friday', 'Fruit': 'Apple'}, 2: {'Day': 'Saturday', 'Fruit': 'Banana'}, 3: {'Day': 'Sunday', 'Fruit': 'Grape'}}利用 enumerate
enumerate 函数将计数器添加到 enumerate 对象的键。因此,在我们的示例中,我们将向
示例
key_list = [1, 2,3]
day_list = ['Friday', 'Saturday','Sunday']
fruit_list = ['Apple','Banana','Grape']
# Given Lists
print("Given key list : " + str(key_list))
print("Given day list : " + str(day_list))
print("Given fruit list : " + str(fruit_list))
# Dictionary creation
res = {val : {"Day": day_list[key], "age": fruit_list[key]}
for key, val in enumerate(key_list)}
# Result
print("The final dictionary : \n" ,res)输出
运行以上代码将获得以下结果 -
Given key list : [1, 2, 3]
Given day list : ['Friday', 'Saturday', 'Sunday']
Given fruit list : ['Apple', 'Banana', 'Grape']
The final dictionary :
{1: {'Day': 'Friday', 'age': 'Apple'}, 2: {'Day': 'Saturday', 'age': 'Banana'}, 3: {'Day': 'Sunday', 'age': 'Grape'}}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP