python列表和字典相互轉化

2021-09-03 08:14:48 字數 793 閱讀 1523

注:列表不能直接使用dict轉換成字典。

方法一:使用zip()函式

a = ['a1','a2','a3','a4']

b = ['b1','b2','b3']

d = zip(a,b)

print(dict(d)) #

將a和b兩個列表內的元素兩兩組合成鍵值對。

當兩個列表的長度不一致時,多出的元素在另乙個列表無匹配的元素時就不展示多出的元素。

方法二:使用巢狀列表轉換為字典

a = ['a1','a2']

b = ['b1','b2']

c = [a,b]

print(dict(c)) #

# 相當於遍歷子列表,如下

dit = {}

for i in c:

dit[i[0]] = i[1]

print(dit)

a和b列表內只能有兩個元素,將列表內的元素自行組合成鍵值對。

注:字典可以直接使用list轉換成列表。

dit = 

# 將字典的key轉換成列表

lst = list(dit)

print(lst) # ['name', 'age', 'gender', 'address']

# 將字典的value轉換成列表

lst2 = list(dit.values())

print(lst2) # ['zxf', '22', 'male', 'shanghai']

字典 元組 列表之間相互轉化 python

coding utf 8 1 字典 dict 字典轉為字串,返回 print type str dict str dict 字典可以轉為元組,返回 age name class print tuple dict 字典可以轉為元組,返回 7,zara first print tuple dict.va...

python 列表與字典相互轉換

1.2個列表轉換為字典 2.使用內建函式 zip 3.求乙個列表中所有資料型別的次數 encoding utf 8 l 1,2,s 1,23 1,2 set 1,2 b 2 d 先用字典定義列表中的資料型別 for i in l if isinstance i,str 判斷字串型別 d str 1 ...

python列表和字典之間的相互轉換

列表轉換成字典 注 列表不能直接使用dict轉換成字典。方法一 使用zip 函式 a a1 a2 a3 a4 b b1 b2 b3 d zip a,b print dict d 將a和b兩個列表內的元素兩兩組合成鍵值對。當兩個列表的長度不一致時,多出的元素在另乙個列表無匹配的元素時就不展示多出的元素...