現在有一個列表,list1 = ['key1','key2','key3'],把他轉為這樣的字典:{'key1':'1','key2':'2',' key3':'3'}
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如何把列表變成字典的詳細內容。更多資訊請關注PHP中文網其他相關文章!