开发者

django/python convert string which represents a python dictionary into a dictionary object

I have a string which represents a python dictionary returned from a db table e.g.

{'name': 开发者_如何转开发'John', 'email': 'test@test.com'}

where {'name': 'John', 'email': 'test@test.com'} is returned as a string from the db

I then have a function which receives a dictionary as **kwargs e.g.

def print_details(*args, **kwargs):
    name = kwargs.pop('name', None)
    email = kwargs.pop('email', None)

    print "%s - %s " % (name, email)

I want to do

dict = DB return value
print_details(dict) 

but I don't know how to convert the string dict into a python dictionary

I am using Django but if there is no way in Django then Python would obviously work as well


ast.literal_eval is a very restricted, safer eval that only evals literals (e.g. dicts, tuple or list literal containing string, int, float, ... literals).

A JSON parser would work as well for an even more restricted subset (bools are different, null instead of None, no tuples, perhaps even more). Again, the standard library can do this (and there are third party solutions for older Python versions).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜