在python中将unicode字符串字典转换为字典

2024-05-15 22:10:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有unicode u"{'code1':1,'code2':1}",我想要字典格式的。

我想要{'code1':1,'code2':1}格式的。

我试过unicodedata.normalize('NFKD', my_data).encode('ascii','ignore')但它返回的是字符串而不是字典。

有人能帮我吗?


Tags: 字符串data字典my格式asciiunicodeencode
3条回答

EDIT:我的假设不正确;因为键没有用双引号(“)括起来,所以字符串不是JSON。See here为了解决这个问题。

我猜你可能是JSON,也就是JavaScript对象表示法。

您可以使用Python的内置json模块执行以下操作:

import json
result = json.loads(u"{'code1':1,'code2':1}")   # will NOT work; see above

您可以使用内置的ast包:

import ast

d = ast.literal_eval("{'code1':1,'code2':1}")

关于模块ast中函数literal求值的帮助:

literal_eval(node_or_string)

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

您可以使用literal_eval。您可能还想确定您正在创建一个dict而不是其他东西。不要使用assert,而是使用自己的错误处理。

from ast import literal_eval
from collections import MutableMapping

my_dict = literal_eval(my_str_dict)
assert isinstance(my_dict, MutableMapping)

相关问题 更多 >