字典 列表 字串轉換關係

2021-09-22 08:21:59 字數 1672 閱讀 7508

字典、列表、字串轉換關係

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

1、現在有兩個列表,list1 = [『key1』,『key2』,『key3』]和list2 = [『1』,『2』,『3』],

把他們轉為這樣的字典:

>>>list1 = ['key1','key2','key3']

>>>list2 = ['1','2','3']

>>>dict(zip(list1,list2))

2、將巢狀列表轉為字典,有兩種方法,

>>>new_list= [['key1','value1'],['key2','value2'],['key3','value3']]

>>>dict(list)

3、定義有序字典-------順序為新增鍵值對的順序,遍歷有序輸出

import cllections

d = collections.ordereddict()

字典轉字串:

str(dict)、json.dumps(dict),無需多說。

字串轉字典:

str格式用eval(str)–二維陣列、json格式用eval(str)或json.loads(str)

import json

dict =

#str構造乙個單引號字典型字串

newdict=str(dict)

print (newdict)

print (newdict[2:5])

print (type(eval(newdict)),eval(newdict))

輸出為:

c:\python36\python3.exe c:/users/administrator/desktop/20190511ceshi.py

nam

字典型字串,鍵由單引號包圍的,不能用json.loads(),只能用eval()

#json.dumps構造乙個雙引號字典型字串

newdict2=json.dumps(dict)

print (newdict2)

print (newdict2[2:5])

print (type(eval(newdict2)),eval(newdict2))

輸出為:

c:\python36\python3.exe c:/users/administrator/desktop/20190511ceshi.py

nam

單引號字典型字串用json.loads()轉字典

需要把單引號轉換成雙引號,這個需要特別注意

strdict =newdict.replace("\'","\"")

print (strdict)

print (json.loads(strdict))

輸出為:

c:\python36\python3.exe c:/users/administrator/desktop/20190511ceshi.py

大家可以把**放一起整體比較一下哦

字典 列表 字串轉換關係

python 列表轉為字典的兩個小方法 1 現在有兩個列表,list1 key1 key2 key3 和list2 1 2 3 把他們轉為這樣的字典 list1 key1 key2 key3 list2 1 2 3 dict zip list1,list2 2 將巢狀列表轉為字典,有兩種方法,new...

列表 字典 字串的相互轉換

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

字典,列表,字串,集合之間的轉換

1 列表轉為字典用dict 例如 列表轉為字典 d e 8 j 4 c 3 y 3 dic dict d print dic 輸出結果 2 字串轉為列表,用list,或者split 直接按照格式來劃分為列表 例如 s eeeeeellllhjjuyiio print list s 結果 e e e ...