Python基础系列python

python 列表转为字典的两个小方法

2019-10-11  本文已影响0人  我爱学python

1、现在有两个列表,list1 = ['key1','key2','key3']和list2 = ['1','2','3'],把他们转为这样的字典:

{'key1':'1','key2':'2','key3':'3'}
list1 = ['key1','key2','key3']
list2 = ['1','2','3']
dict(zip(list1,list2))
{'key1':'1','key2':'2','key3':'3'}

2、将嵌套列表转为字典,有两种方法,

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
dict(list)
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}

或者这样:

new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
new_dict = {}
for i in new_list:
    new_dict[i[0]] = i[1]                #字典赋值,左边为key,右边为value

new_dict
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}

示例:

tu = ['alex','seven']
li_val = []
for i in range(len(tu)):
    li_val.append(i+10)
print(li_val)
new_dict = dict(zip(li_val,tu))
print(new_dict)
上一篇下一篇

猜你喜欢

热点阅读