繁体   English   中英

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

[英]how to convert a string variable to dictionary

我使用 python 并且我想知道如何转换包含以下内容的字符串变量:

"OrderedDict([('bagging_freq', 2), ('colsample_bytree', 0.98), ('learning_rate', 0.13)])"

字典变量:

{'bagging_freq': 2, 'colsample_bytree': 0.98, 'learning_rate': 0.13}

一种简单的方法是使用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) 

Output:

{'bagging_freq': 2, 'colsample_bytree': 0.98, 'learning_rate': 0.13}

*** 请注意,从安全角度来看, eval确实不安全 ***

暂无
暂无

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

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