python将列表转换成字典应用场景

1. 方法一使用zip()函数:

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表

i = [1,2,3]  #定义列表1
l = ['a','b','c'] #定义列表2
d= zip(l,i) #将对象l作为参数,将元素打包成元组,返回元素的列表
print(dict(d))
i = [1,2,3]
l = ['a','b','c']
d = list(zip(l,i))
print(d)
print(dict(d))

  zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。

方法二: 使用嵌套列表转换为字典

a = ['a1','a2']
b = ['b1','b2']
c = [a,b]
print(c)
# 相当于遍历子列表,如下
dit = {}
for i in c:
    dit[i[0]] = i[1]
print(dit)

  注:a和b列表内只能有两个元素,将列表内的元素自行组合成键值对

posted @ 2021-05-16 16:36  sunshine阿星  阅读(375)  评论(0)    收藏  举报