简体   繁体   中英

Convert redis hash to python dict?

Suppose I have a python dict aa = {"name": "nilesh", "age":29} When I store it in redis hash, all datatypes changes to string.

import redis
r = redis.StrictRedis()
r.hmset("nilesh_123", aa)
bb = r.hgetall("nilesh_123")

Now bb comes as {'age': '29', 'name': 'nilesh'} . Is is there any pythonic way to convert this hash returned value to python dict format again ? One way which I see is to store all the datatypes of dictionary values somewhere and then convert them again when I get that hash by iterating the redis hash value, but I am looking for better pythonic solution.

I can store the dict as pickled object in a redis string and then get it and loads it again using pickle, but I am more interested in using hashes compare to strings.

 {'age': '29', 'name': 'nilesh'} 

is JSON format, try to look for tools that can convert JSON to python dict like:

Converting JSON into Python dict

Well, i wouldn't say pythonic way but

mydict = eval("{'age': '29', 'name': 'nilesh'}")

or (slightly) better ast.literal_eval yet, some say eval is evil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM