Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลง String Representation ของ Dictionary เป็น Dict ใน Python

วิธีที่ 1: ใช้ ast.literal_eval() (ปลอดภัย)

s = "{'baz': 'lol', 'foo': 'bar'}"
import ast
s = ast.literal_eval(s)
print(s['foo'], s['baz'])

ผลลัพธ์

bar lol

วิธีที่ 2: ใช้ json.loads() (ต้องเป็น valid JSON ใช้ double quotes)

>> import json
>>> x = json.loads('{"foo": "bar", "hello": "world"}')
>>> type(x)