[文字處理篇] 各種資料型態與字串互轉 - tsungjung411/python-study GitHub Wiki
str 轉 dict
Case1
x = "{'A':'1', 'B':2, 'C':'3'}"
eval(x)
執行結果:
{'A': '1', 'B': 2, 'C': '3'}
Case2
s = '{"name": "tj_tsai", "age": 25, "account": "tsungjung411", "is_man": True}'
dict = eval(s)
print('dict:', dict)
print('dict: name: %s (type: %s)' % (dict['name'], type(dict['name'])))
print('dict: age: %s (type: %s)' % (dict['age'], type(dict['age'])))
print('dict: is_man: %s (type: %s)' % (dict['is_man'], type(dict['is_man'])))
執行結果:
dict: {'name': 'tj_tsai', 'age': 25, 'account': 'tsungjung411', 'is_man': True}
dict: name: tj_tsai (type: <class 'str'>)
dict: age: 25 (type: <class 'int'>)
dict: is_man: True (type: <class 'bool'>)