我使用python,我想知道如何转换包含以下内容的字符串变量:
"OrderedDict([('bagging_freq', 2), ('colsample_bytree', 0.98), ('learning_rate', 0.13)])"到字典变量:
{'bagging_freq': 2, 'colsample_bytree': 0.98, 'learning_rate': 0.13}发布于 2020-06-23 15:57:39
一个简单的方法是使用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}*请注意,从安全的角度来看eval确实是不安全的*
https://stackoverflow.com/questions/62538849
复制相似问题