Search code examples
pythondictionaryabstract-syntax-tree

ast.literal_eval() on a dict which has a null key value


I am trying to convert a string to a dictionary using literal_eval(), the only issue I am facing here is I have a null in one of the dictionary values.

attributes = '{"New Value": "United States", "Old Value": null, "Reason": "lorem ipsum", "Source": "Action"}'

This is my input dict which I am casting into a string before passing to literal_eval(). when I do a literal eval using the code:

attributes_new = ast.literal_eval(attributes)

and I get this error when the code runs:

ValueError: malformed node or string: <ast.Name object at 0x1066efa30>

Is there a way I can replace this null with a None so that it doesn't fail or if there is a better and optimised solution, it is welcome. Thanks in advance.


Solution

  • attributes_new = ast.literal_eval(attributes.replace('null', 'None'))
    

    ...is what I'd do as it is simple and readable.


    Edit: I just noticed it looks suspiciously a lot like JSON. Maybe use json.loads instead.