在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ python字符串轉(zhuǎn)化為字典的疑問?

python字符串轉(zhuǎn)化為字典的疑問?

import json
dir=r"C:\Users\Administrator\Desktop"
file_nm="新建文本文檔 (2).txt"
f=open(dir+"\\"+file_nm,"r")
r=json.load(f)
print(r["people"],type(r["people"]))
print("*******")
print(r["people"][0],type(["people"][0]))
t=dict(r["people"][0])
print(t,type(t))

結(jié)果為
[{'firstName': 'Brett', 'lastName': 'McLaughlin'}, {'firstName': 'Jason', 'lastName': 'Hunter'}] <class 'list'>
+++++++++++++
{'firstName': 'Brett', 'lastName': 'McLaughlin'} <class 'str'>
{'firstName': 'Brett', 'lastName': 'McLaughlin'} <class 'dict'>

疑問:
字符串
{'firstName': 'Brett', 'lastName': 'McLaughlin'}可以用dict()的方式轉(zhuǎn)化為字典,
但是我寫
s=r"{'1':'2','3':'4'}"
ss=dict(s)
就會報(bào)錯:
Traceback (most recent call last):
File "E:/pythontest/GUI/testfield.py", line 13, in <module>

ss=dict(s)

ValueError: dictionary update sequence element #0 has length 1; 2 is required
為什么這個字符串不能轉(zhuǎn)化為字典?

回答
編輯回答
獨(dú)特范

誰告訴你字符串可以直接用dict()轉(zhuǎn)換為字典的?

2017年2月23日 10:25
編輯回答
毀與悔
print(r["people"][0],type(["people"][0]))

注意這一句,你打印的其實(shí)是["people"][0],也就是'people'的類型,自然是str,而r["people"][0]還是一個字典。

t=dict(r["people"][0])

這里只是把字典轉(zhuǎn)換為字典,自然沒有問題。
所以事實(shí)上dict不能將字符串轉(zhuǎn)換為字典,只有json相關(guān)的函數(shù)才可以。

2017年4月25日 05:21