如何反序列化一个python打印字典? [英] how to deserialize a python printed dictionary?

查看:134
本文介绍了如何反序列化一个python打印字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python的str字典表示在数据库中作为varchars,我想检索原始的python字典



如何再次有字典,基于str一个字典的表示?



示例



 >> ; dic = {u'key-a':u'val-a',key-b:val-b} 
>>> dicstr = str(dic)
>>>> dicstr
{'key-b':'val-b',u'key-a':u'val-a'}

在这个例子中,将dicstr转换成可用的python字典。

解决方案

p>使用 ast.literal_eval(),对于这种情况,喜欢 repr() over str (),因为 str()不保证字符串可以转换回有用对象。

 在[7]中:import ast 

在[10]中:dic = {u'key-a':u'val- a',key-b:val-b}

在[11]中:strs = repr(dic)

在[12]中:strs
Out [12]:{'key-b':'val-b',u'key-a':u'val-a'}

在[13]中:ast .literal_eval(strs)
输出[13]:{u'key-a':u'val-a','key-b':'val-b'}


I have python's str dictionary representations in a database as varchars, and I want to retrieve the original python dictionaries

How to have a dictionary again, based in the str representation of a dictionay?

Example

>>> dic = {u'key-a':u'val-a', "key-b":"val-b"}
>>> dicstr = str(dic)
>>> dicstr
"{'key-b': 'val-b', u'key-a': u'val-a'}"

In the example would be turning dicstr back into a usable python dictionary.

解决方案

Use ast.literal_eval() and for such cases prefer repr() over str(), as str() doesn't guarantee that the string can be converted back to useful object.

In [7]: import ast

In [10]: dic = {u'key-a':u'val-a', "key-b":"val-b"}

In [11]: strs = repr(dic)

In [12]: strs
Out[12]: "{'key-b': 'val-b', u'key-a': u'val-a'}"

In [13]: ast.literal_eval(strs)
Out[13]: {u'key-a': u'val-a', 'key-b': 'val-b'}

这篇关于如何反序列化一个python打印字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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