如何将Unicode字符串转换为字典?

编程入门 行业动态 更新时间:2024-10-25 10:28:53
本文介绍了如何将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字符串转换为字典?

本文发布于:2023-11-02 17:49:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1553023.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   如何将   字典   Unicode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!