Skip to content Skip to sidebar Skip to footer

Using Ast.literal_eval On A Nested Dictionary

I'm using ast.literal_eval to change the data I receive from json.loads() into a Python dictionary; however if I should just be going about this an entirely different way - feel fr

Solution 1:

ast.literal_eval has no problem with nested dictionaries:

>>> ast.literal_eval("{'a': {'b':'c'}}")
{'a': {'b': 'c'}}

ast.literal_eval is breaking because the data are, in fact, JSON… And JSON is not valid Python. Specifically, null is not a valid Python literal.

Why not just use json.loads() to load the data?


Solution 2:

I came up with one scenario where in I wanted to use json.normalize in pandas but values were of str type. using ast.literal_eval, i type casted

You can use ast.literal_eval like below - df[column_name] = df[column_name].apply(ast.literal_eval)

this will convert str to dict. for eg. df = [{'A': "{'value': '1'}", 'B': "{'value': '2'}"}]

after applying literal eval - df = [{'A': {'value': '1'}, 'B': {'value': '2'}}]


Post a Comment for "Using Ast.literal_eval On A Nested Dictionary"