简体   繁体   English

我如何从_ast.Dict变成实际的dict?

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

i have an ast object that returns type '_ast.Dict' 我有一个ast对象,返回的类型为“ _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()

There are two decent ways to go about getting a regular Python dictionary from an _ast.Dict . _ast.Dict获取常规Python字典有两种不错的方法。 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)) . 如果您的ast.Dict实例包含常规Python对象(例如列表和字符串),则可以使用dict(zip(d.keys, d.values))将其直接转换为常规dict

However, if your dictionary contains other ast nodes rather than the corresponding regular objects (eg ast.Str for strings and ast.Num for numbers), you probably want to recursively evaluate everything. 但是,如果您的字典包含其他ast节点而不是相应的常规对象(例如ast.Str表示字符串, ast.Num表示数字),则您可能希望递归地评估所有内容。 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. 我看到的最好的方法是将字典包装在ast.Expression ,然后将其传递给内置的compile函数,以将其转换为代码对象。 The code object can then be passed to eval . 然后可以将代码对象传递给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 . 在您的示例中,我怀疑item已经是ast.Expression了,因此您可以跳过将ast.DictExpression的步骤。 You can get a regular dict with: 你可以得到一个普通dict有:

dct = eval(compile(item, "<ast expression>", "eval"))

Try this: 尝试这个:

my_dict = ast.Dict(keys=('first','second'), values=(1,2))

print type(my_dict)                   #<class '_ast.Dict'>

answer = dict(zip(t.keys,t.values))
print answer                          #{'second': 2, 'first': 1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM