示例 1:使用 zip 和 dict 方法
index = [1, 2, 3]
languages = ['python', 'c', 'c++']
dictionary = dict(zip(index, languages))
print(dictionary)
输出
{1: 'python', 2: 'c', 3: 'c++'}
我们有两个列表:index
和 languages
。它们首先被压缩,然后转换为一个字典。
示例 2:使用列表推导式
index = [1, 2, 3]
languages = ['python', 'c', 'c++']
dictionary = {k: v for k, v in zip(index, languages)}
print(dictionary)
输出
{1: 'python', 2: 'c', 3: 'c++'}
这个示例与示例 1 类似;唯一的区别是,这里使用列表推导式进行压缩,然后使用 { }
将其转换为字典。
在Python 列表推导式中了解更多关于列表推导式的信息。