时间:2021-07-01 10:21:17 帮助过:78人阅读
python将列表变字典的两种方法:
1、方法:再构造一个列表list2 = [‘1’,‘2’,‘3’],使用zip转换为元组后,在将元组转换为字典。
相关推荐:《python视频教程》
list1 = ['key1','key2','key3'] list2 = ['1','2','3'] dict(zip(list1,list2)) {'key1':'1','key2':'2','key3':'3'}
2、将嵌套列表转为字典,有两种方法,
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'}
以上就是python如何把列表变字典的详细内容,更多请关注Gxl网其它相关文章!