一、使用zip函数
zip函数是Python内置的一个强大工具,它可以将多个迭代器(如列表、元组等)"压缩"成一个迭代器,其中每个元素都是一个元组。使用zip函数将两个列表转换为字典是最常见的方法。
1、基本用法
python
keys = ['a', 'b', 'c']
values = [1, 2, 3]
a = zip(keys, values)
print(type(a))
print(a)
print(next(a))
print(next(a))
dictionary = dict(zip(keys, values))
print(dictionary)
结果:
python
<class 'zip'>
<zip object at 0x10523cf40>
('a', 1)
('b', 2)
{'a': 1, 'b': 2, 'c': 3}
在这个例子中,zip(keys, values)生成一个迭代器,其中每个元素都是一个元组,dict函数接收这个迭代器并将其转换为字典。
2、处理不同长度的列表
当两个列表长度不同时,zip函数会根据较短的列表截断。
python
keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # 输出: {'a': 1, 'b': 2, 'c': 3}
如果需要处理长度不同的列表而不截断,可以使用itertools.zip_longest
python
import itertools
keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3]
dictionary = dict(itertools.zip_longest(keys, values, fillvalue=None))
print(dictionary)
# 输出: {'a': 1, 'b': 2, 'c': 3, 'd': None}
二、字典推导式
字典推导式是一种简洁的创建字典的方法,类似于列表推导式。它可以用来将两个列表转换为字典。
python
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = {keys[i]: values[i] for i in range(len(keys))}
print(dictionary) # 输出: {'a': 1, 'b': 2, 'c': 3}
三、使用for循环
python
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = {}
for i in range(len(keys)):
dictionary[keys[i]] = values[i]
print(dictionary) # 输出: {'a': 1, 'b': 2, 'c': 3}