需要帮助在python中将字符串转换为字典

斯里拉姆

我正在 AWS 中创建一个 lambda 函数来执行 SSM 自动化文档。

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm.html#SSM.Client.start_automation_execution

response = client.start_automation_execution(
DocumentName='XYZ',
Parameters={...}    

)

我已将 DocumentName 和 Parameters 值存储在 dynamodb 表中,如下所示。

"parameters_name": { "S": "'ParameterName1': [Variable1] , 'ParameterName2': [Variable2] , 'ParameterName3': [variable3] , 'ParameterName4': [Variable4] " }, "document_name": { "S": "XYZ" }

** 变量值作为字符串从事件中获得。

参数的定义在 boto3 文档中如下:

Parameters (dict) -- A key-value map of execution parameters, which match the declared parameters in the Automation runbook. (string) -- (list) -- (string) --

有没有办法将字符串转换为字典到以下格式:

{'ParameterName1': [Variable1] , 'ParameterName2': [Variable2] , 'ParameterName3' : [Variable3], 'ParameterName4' : [Variable4]}

丹尼尔·C·雅各布斯

Python 有一个eval为此调用的内置函数

# need to append and prepend curly braces to the string first
my_str = "{'ParameterName1': [Variable1], 'ParameterName2': [Variable2], 'ParameterName3': [Variable3], 'ParameterName4': [Variable4]}"
my_dict = eval(my_str)

print(str(my_dict))

您还可以使用ast声称比 更安全库,eval但这是因为它对字符串的格式实施了更严格的规则。

import ast

my_str = "{'ParameterName1': [Variable1], 'ParameterName2': [Variable2], 'ParameterName3': [Variable3], 'ParameterName4': [Variable4]}"
my_dict = ast.literal_eval(my_str)

print(str(my_dict))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章