Python将字符串对象转换为字典 [英] Python convert string object into dictionary

查看:151
本文介绍了Python将字符串对象转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力构建一个复杂的数据结构,它将返回一个字典。目前该类返回字符串对象的形式

  {
cset:x,
b1:y,
b2:z,
dep:{
cset:x1,
b1:y1,
b2:z1,
dep:{
cset:x2,
b1:y2,
b2:z2,
dep:< same as above.it recurses few more levels>
...
}
}
}

我想将这个整个字符串对象转换成字典。
我读了一篇文章以使用 pickle 模块,但我不想将其序列化为某些文件并使用它。



参考: http://bytes.com/topic/python/answers/36059-convert-dictionary-string-vice-versa



我正在寻找其他



很高兴知道任何这样的方式。

解决方案

不要使用 eval 。如果您确定字符串将始终包含有效的Python dict ,请使用 ast.literal_eval 。这样做非常像 eval ,但它只评估表达式是否是有效的 dict 列表等,如果不是,则抛出异常。这比尝试评估在运行时可能包含任意代码的字符串更安全。



docs


安全评估表达式节点或
a字符串包含一个Python
表达式。提供的字符串或节点
可能只包含以下Python文字结构之后的

字符串,数字,元组,列表,
dicts,booleans和None。



这可以用于安全评估
字符串,其中包含来自不受信任源的Python表达式
,而
需要自己解析值。


代码示例:

 >> > import ast 
>>>> ast.literal_eval(1 + 1)
追溯(最近的最后一次呼叫):
文件< stdin>,第1行,< module>
文件/usr/lib/python2.6/ast.py,第68行,literal_eval
返回_convert(node_or_string)
文件/usr/lib/python2.6/ast .py,第67行,_convert
raise ValueError('malformed string')
ValueError:格式错误的字符串
>>> ast.literal_eval(\1 + 1\)
'1 + 1'
>>> ast.literal_eval({'a':2,'b':3,3:'xyz'})
{'a':2,3:'xyz','b':3}


I have been working to build a complex data structure which would return a dictionary. Currently that class return string object of the form

{
   cset : x,    
   b1   : y,
   b2   : z,    
   dep  : {    
              cset : x1,
              b1   : y1,    
              b2   : z1,    
              dep  : {    
                         cset : x2,     
                         b1   : y2,    
                         b2   : z2,    
                         dep  : <same as above.it  recurses few more levels>                         
                         ...  
                     }
        }
    }

I want to convert this whole string object into dictionary. I read on one of the articles to use pickle module, but I don't want to serialize it into some file and use it.

Ref : http://bytes.com/topic/python/answers/36059-convert-dictionary-string-vice-versa

I am looking for some other neater ways of doing it, if possible.

Would be great to know any such ways.

解决方案

Don't use eval. If you are sure that the string will always contain a valid Python dict, use ast.literal_eval. This works pretty much like eval, but it only evaluates if the expression is a valid dict,list, etc. and throws an exceptions if it isn't. This is way safer than trying to evaluate strings that may contain arbitrary code at runtime.

From the docs:

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.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

Code Example:

>>> import ast
>>> ast.literal_eval("1+1")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string
>>> ast.literal_eval("\"1+1\"")
'1+1'
>>> ast.literal_eval("{'a': 2, 'b': 3, 3:'xyz'}")
{'a': 2, 3: 'xyz', 'b': 3}

这篇关于Python将字符串对象转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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