python 列表轉為字典的兩個小方法

MHyourh發表於2020-10-07

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'}

或者這樣:

'''
遇到問題沒人解答?小編建立了一個Python學習交流QQ群:778463939
尋找有志同道合的小夥伴,互幫互助,群裡還有不錯的視訊學習教程和PDF電子書!
'''
>>>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'}
Henry

相關文章