简体   繁体   中英

how to convert string dict to dictonary in python

a= {'Locator__creation_date': {'start': datetime.date(2013, 11, 14), 'end': datetime.date(2013, 11, 14)}, 'Locator__employed': u'True', 'Locator__employer_state': u'AL', 'Locator__receiving_hiv_treatment': u'True', 'Locator__hiv_treatment_state': u'AR', 'Locator__mental_health_provider': u'False', 'Locator__parole': u'True', 'Locator__parole_state': u'IA', 'data_model_name': ['Locator']}

ast.literal_eval(a)

it gives

ValueError: malformed string

Presumably you meant a to be a string:

a = "{'Locator__creation_date': {'start': datetime.date(2013, 11, 14), 'end': datetime.date(2013, 11, 14)}, 'Locator__employed': u'True', 'Locator__employer_state': u'AL', 'Locator__receiving_hiv_treatment': u'True', 'Locator__hiv_treatment_state': u'AR', 'Locator__mental_health_provider': u'False', 'Locator__parole': u'True', 'Locator__parole_state': u'IA', 'data_model_name': ['Locator']}"

This won't work because datetime.date(...) is not a Python literal. It is a representation of a Python datetime.date() object, and ast.literal_eval() does not handle arbitrary types.

Only Python literal values ( {...} for dictionaries or sets, [...] for lists, (...) for tuples, digits to numbers and string literals such as u'...' and r'...' and '...' with the various quote variations) are handled. See the Literals section of the Python expressions documentation and the ast.literal_eval() documentation itself:

The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None .

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