當前位置:成語大全網 - 新華字典 - python 數組 變成 字典的方法

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、將嵌套 列表 轉為 字典 ,有兩種方法,

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