如何将字符串变量转换为字典

时间:2020-06-23 15:55:04

标签: python

我使用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}

1 个答案:

答案 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}

***请注意,从安全角度来看,评估实际上 不安全***