簡體   English   中英

我如何從_ast.Dict變成實際的dict?

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

我有一個ast對象,返回的類型為“ _ast.Dict”

如何將其轉換為常規字典?

我的失敗嘗試-

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()

_ast.Dict獲取常規Python字典有兩種不錯的方法。 哪個更好取決於字典的內容。

如果您的ast.Dict實例包含常規Python對象(例如列表和字符串),則可以使用dict(zip(d.keys, d.values))將其直接轉換為常規dict

但是,如果您的字典包含其他ast節點而不是相應的常規對象(例如ast.Str表示字符串, ast.Num表示數字),則您可能希望遞歸地評估所有內容。 我看到的最好的方法是將字典包裝在ast.Expression ,然后將其傳遞給內置的compile函數,以將其轉換為代碼對象。 然后可以將代碼對象傳遞給eval

在您的示例中,我懷疑item已經是ast.Expression了,因此您可以跳過將ast.DictExpression的步驟。 你可以得到一個普通dict有:

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

嘗試這個:

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