本文介绍了如何将Unicode字符串转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用utf-8编码的字符串,例如
I have a string with utf-8 encoding, like
>>> print s "{u'name':u'Pradip Das'}"基本上,我从JSON文件加载了一些数据,并且如上所述加载. 现在,我想将此字符串隐藏到python字典中.所以我可以这样:
Basically I load some data from JSON file and it loads as above. Now, I want to covert this string in to python dictionary. So I can do like:
>>> print d['name'] 'Pradip Das'推荐答案
您可以使用内置的 ast.literal_eval :
You can use the built-in ast.literal_eval:
>>> import ast >>> a = ast.literal_eval("{'a' : '1', 'b' : '2'}") >>> a {'a': '1', 'b': '2'} >>> type(a) <type 'dict'>这比使用eval更安全.正如文档本身所建议的那样:
This is safer than using eval. As the docs itself recommends it:
>>> help(ast.literal_eval) Help on function literal_eval in module ast: 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.此外,您还可以阅读文章,该文章将说明您为什么应避免使用eval.
Additionally, you can read this article which will explain why you should avoid using eval.
更多推荐
如何将Unicode字符串转换为字典?
发布评论