Python 如何使用列表推导式创建字典

Python 如何使用列表推导式创建字典

通过在Python中使用dict()方法,我们可以使用列表推导式创建一个Python字典。dict()方法的语法如下所示。以下是此语法:

dict(**kwarg)

关键字参数。我们可以传递一个或多个关键字参数。如果没有传递关键字参数,则dict()方法将创建一个空的字典对象。使用列表推导来创建字典的语法:

dict(list_comprehension)

使用列表推导创建字典

我们需要发送一个包含键值对的元组列表到dict()方法,而不是发送一些关键字。让我们通过一个例子来使用列表推导创建一个字典。

示例1

dict_= dict([(chr(i), i) for i in range(100, 105)])
print('Output dictionary: ', dict_)
print(type(dict_))

输出

Output dictionary:  {'d': 100, 'e': 101, 'f': 102, 'g': 103, 'h': 104}
<class 'dict'>

在列表推导中,我们使用了range()方法来迭代for循环。同时,我们还使用了另一个Python内置函数chr()来获取Unicode整数的字符串表示。在输出字典中,键是由Unicode整数的字符串表示创建的,值是由循环整数创建的。

示例2

在这个示例中,我们使用Python的zip()方法将两个输入列表”data1″和”data2″传递给list_comprehension。这个zip()方法根据两个输入创建一个迭代器,最后通过使用列表推导式创建字典。

data1 = [1, 2, 3, 4, 5]
data2 = [10, 20, 30, 40, 50]
print('input list1: ', data1)
print('input list12: ', data2)

# create a dict using list comprehension
d = dict([(key, value) for key, value in zip(data1,data2)])
print('Output dictionary: ', d)
print(type(d))

输出

input list1:  [1, 2, 3, 4, 5]
input list12:  [10, 20, 30, 40, 50]
Output dictionary:  {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
<class 'dict'>

示例3

在以下示例中,使用Python的列表推导技术,我们创建了一个包含元组的列表,每个元组有2个元素。然后,这两个元素被转换为键和值,存储在字典对象中。

l = [( i,i*2) for i in range(1,10)]
print("Comprehension output:",l)

dict_= dict(l)
print('Output dictionary: ', dict_)
print(type(dict_))

输出

Comprehension output: [(1, 2), (2, 4), (3, 6), (4, 8), (5, 10), (6, 12), (7, 14), (8, 16), (9, 18)]
Output dictionary:  {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
<class 'dict'>

示例4

最后让我们来看一个例子,看看如何在Python中使用列表推导式创建一个字典。

l = [20, 21, 65, 29, 76, 98, 35]
print('Input list: ', l)

# create a dict using list comprehension
d = dict([(val/2, val) for val in l])
print('Output dictionary: ', d)
print(type(d))

输出

Input list:  [20, 21, 65, 29, 76, 98, 35]
Output dictionary:  {10.0: 20, 10.5: 21, 32.5: 65, 14.5: 29, 38.0: 76, 49.0: 98, 17.5: 35}
<class 'dict'>

通过使用列表推导来迭代列表元素,我们成功地创建了一个字典。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程