【Python】dict和list相互轉換(字典和列表相互轉換)

        在之前博文(https://blog.csdn.net/Jarry_cm/article/details/104914405)中,已經介紹了String和List之間的轉換,這篇主要介紹dict和list之間的轉換。

目錄

1.List轉dict

1.1For循環

1.2嵌套列表

1.3zip函數

2.dict轉List

2.1list函數--取key值

2.2list函數--取value值 

2.3for循環


1.List轉dict

1.1For循環

seg_list=['有些', '有']
dict = {}
for i in range(len(seg_list)):
    dict[i]=seg_list[i]

print (dict)

結果:

{0: '有些', 1: '有'}

1.2嵌套列表

嵌套列表,有兩種實現方式:

方法1:

dic = {}
seg_list = ['有些', '有']
seg_index = [0,1]
seg = [seg_index,seg_list]
print(dict(seg))

結果:

{0: 1, '有些': '有'}

方法2:除了上面的組合方式,也可以用for循環

dic = {}
seg_list = ['有些', '有']
seg_index = [0,1]
for i in seg:
    dic[i[0]] = i[1]
print(dic)

 結果:

{0: 1, '有些': '有'}

1.3zip函數

seg_list = ['有些', '有']
seg_index = [0,1]
seg = zip(seg_index,seg_list)
print(dict(seg))

結果:

{0: '有些', 1: '有'}

2.dict轉List

2.1list函數--取key值

list函數默認是將字典中的key取出來,返回list

dit = {'a1':'name1',
       'a2':'name2',
       'a3':'name3'}
lst = list(dit)
print(lst)

結果:

['a1', 'a2', 'a3']

當然,也可以用以下方式:

dit = {'a1':'name1',
       'a2':'name2',
       'a3':'name3'}
lst = list(dit.keys())
print(lst)

結果:

['a1', 'a2', 'a3']

2.2list函數--取value值 

dit = {'a1':'name1',
       'a2':'name2',
       'a3':'name3'}
lst = list(dit.values())
print(lst)

結果:

['name1', 'name2', 'name3']

2.3for循環

for循環是最原始的方式,其實就是對字典進行遍歷,再放入list中,以下直接對key和value同時進行遍歷。

dit = {'a1':'name1',
       'a2':'name2',
       'a3':'name3'}
lst_key=[]
lst_value=[]
for key,value in dit.items():
    lst_key.append(key)
    lst_value.append(value)
print (lst_key)
print (lst_value)    
    

結果:

['a1', 'a2', 'a3']
['name1', 'name2', 'name3']

以上就是dict和list轉換的方法了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章