Python Pickle与Stringify
目前,我正在使用Python Pickle与Stringify,python,performance,redis,pickle,Python,Performance,Redis,Pickle,目前,我正在使用str()对字典进行字符串化,然后将其存储在redis中。当我想修改对象时,我从redis获得它并使用eval()。我发现也可以使用pickle模块来做同样的事情。哪一个更有效,哪一个更好 obj = # very large and deeply nested dictionary cache = redis.StrictRedis(host='localhost', port=6379, db=0) cache.set('id', str(obj)) cache.get('i
str()
对字典进行字符串化,然后将其存储在redis中。当我想修改对象时,我从redis获得它并使用eval()
。我发现也可以使用pickle模块来做同样的事情。哪一个更有效,哪一个更好
obj = # very large and deeply nested dictionary
cache = redis.StrictRedis(host='localhost', port=6379, db=0)
cache.set('id', str(obj))
cache.get('id')
或
因为您使用的是嵌套字典,而redis仅支持 Redis哈希是字符串字段和字符串值之间的映射 然后是使用
json
模块的最简单方法
import json
your_dict = {}
json.dumps(your_dict)
# and to load it
your_dict_in_str = '{}'
json.loads(your_dict_in_str)
并尽量避免使用
eval
为什么不使用json.dumps?既然redis支持dict,为什么不使用它?@vishes\u shell redis支持嵌套字典?哦,我不知道。这取决于你的消费者在做什么,不是吗?我建议JSON不要提供其他信息,但是。。。这要看情况了。@Soubriquet对不起,我想它不支持嵌套的。看看@Soubriquet,因为有效的json与“
一起,而不是”
,所以有效的转储json是“{”nest:{”hello:“world”},“loss:[],“pid”:0,“val:[0.0]}”
import json
your_dict = {}
json.dumps(your_dict)
# and to load it
your_dict_in_str = '{}'
json.loads(your_dict_in_str)