Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i go from an _ast.Dict to an actual dict?

i have an ast object that returns type '_ast.Dict'

how do i convert that into a regular dict?

my failed attempts -

type(item.value) -> <type '_ast.Dict'>

eval(item.value) -> *** TypeError: eval: argument 1 must be string or code object

ast.parse(item.value,mode="eval") -> *** TypeError: expected a readable buffer object

dict(item.value) -> *** TypeError: '_ast.astlist' object is not callable

len(item.value) -> *** TypeError: object of type '_ast.Dict' has no len()
like image 393
Matthew Kime Avatar asked Dec 06 '25 14:12

Matthew Kime


1 Answers

There are two decent ways to go about getting a regular Python dictionary from an _ast.Dict. Which is better may depend on what the contents of the dictionary are.

If your ast.Dict instance contains regular Python objects (like lists and strings), you can directly convert it to a regular dict with dict(zip(d.keys, d.values)).

However, if your dictionary contains other ast nodes rather than the corresponding regular objects (e.g. ast.Str for strings and ast.Num for numbers), you probably want to recursively evaluate everything. The best way I see to do this is to wrap your dictionary in an ast.Expression, then pass it to the built in compile function to turn it into a code object. The code object can then be passed to eval.

In your example, I suspect that item is an ast.Expression already, so you can skip the step of packing the ast.Dict into an Expression. You can get a regular dict with:

dct = eval(compile(item, "<ast expression>", "eval"))
like image 54
Blckknght Avatar answered Dec 08 '25 05:12

Blckknght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!