Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chuyển string thành dictionary trong Python

Dùng ast.literal_eval() evaluate string như Python expression. An toàn evaluate expression node hoặc string chứa Python expression. String/node chỉ chứa literal structure: string, number, tuple, list, dict, boolean, None. Ví dụ:

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

Dict cũng xem như JSON string. Dùng module json convert string thành dict. Ví dụ:

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