Python - 将字符串分解为嵌套的字典键

标签 python

我有一个字符串:candidate__name__first_name。我想将其转换为以下形式的嵌套字典:

{ 
  candidate: {
    name: {
      first_name: 'MyName'
    }
  }
}

执行此操作的最佳方法是什么?

最佳答案

这个怎么样:

recursive_key = 'candidate__name__first_name'
value = 'MyName'
for key in reversed(recursive_key.split('__')):
    value = {key: value}
print(value)

关于Python - 将字符串分解为嵌套的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41757835/

相关文章:

python - 为 keras reshape 数组

python - 在 Keras 中训练多元回归模型时损失值非常大

python - 需要拆分具有混合数据的列

python - 数据帧属性错误: 'Index' object has no attribute 'date'

python - 如何绘制 1000 像素的图?

python - 一定次数的迭代后打开一个新的 CSV 文件

python - 如何检查 float 列表的总和是否为整数?

Java使用PythonInterpreter调用Python函数

python - Pylint 消息 : Invalid constant name (invalid-name)

python - 使用Regex从Elasticsearch中的json输出中提取电子邮件地址