圆月山庄资源网 Design By www.vgjia.com

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、将嵌套列表转为字典,有两种方法,

>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,列表转为字典

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com