如何将Unicode字符串转换为字典? [英] How to convert Unicode string to dictionary?

查看:317
本文介绍了如何将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'

推荐答案

您可以使用内置的

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字符串转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆