1

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

{'name': 'John', 'email': '[email protected]'}

where {'name': 'John', 'email': '[email protected]'} 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

10
  • 2
    "string dict into a python dictionary"? Did you try eval()? What was wrong with that? Commented Feb 17, 2011 at 11:15
  • @S.Lott: There are several things wrong with eval, not only in OP's case ;) Commented Feb 17, 2011 at 11:18
  • 2
    A database containing strings that represent Python dicts? That sounds like it's breaking all kinds of rules of database normalization... Commented Feb 17, 2011 at 13:12
  • @delnan: several things wrong with eval()? Do tell. Commented Feb 17, 2011 at 14:05
  • @S.Lott: It's slow, can easily lead to security problems or hard-to-debug errors, therefore requies exsessive validation (i.e. not hard to use properly even when warranted), and of course it's usually the wrong (too powerful) tool for the job. Commented Feb 17, 2011 at 14:12

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.