我使用python,我想知道如何转换包含以下内容的 string 变量:
"OrderedDict([('bagging_freq', 2), ('colsample_bytree', 0.98), ('learning_rate', 0.13)])"
到字典变量:
{'bagging_freq': 2, 'colsample_bytree': 0.98, 'learning_rate': 0.13}
答案 0 :(得分:1)
一种简单的方法是使用eval
:
from collections import OrderedDict
s = "OrderedDict([('bagging_freq', 2), ('colsample_bytree', 0.98), ('learning_rate', 0.13)])"
s = eval(s)
# this results in :
# OrderedDict([('bagging_freq', 2),
# ('colsample_bytree', 0.98),
# ('learning_rate', 0.13)])
# now, if you'd like to convert that to a 'regular' duct, just do:
dict(s)
输出:
{'bagging_freq': 2, 'colsample_bytree': 0.98, 'learning_rate': 0.13}
***请注意,从安全角度来看,评估实际上 不安全***