将字符串转换为嵌套字典 [英] Converting a string to a nested dictionary
本文介绍了将字符串转换为嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,我想将其转换为Python中的嵌套字典.
I have a string which I want to convert to a nested dictionary in Python.
示例输入:
import copy
diff_str = "/pathConstraint/latency/latencyValue"
value = "low"
diff_arr = diff.split("/")
final_temp_dict = dict()
for elem in reversed(diff_arr):
if len(final_temp_dict) == 0:
final_temp_dict.setdefault(elem, value)
else:
temp_final_dict = copy.deepcopy(final_temp_dict)
final_temp_dict.setdefault(elem, temp_final_dict)
print (final_temp_dict)
运行此程序时,我遇到错误,但没有得到预期的输出.
While running this I face an error and I'm not getting the expected output.
所需的输出为嵌套字典:
The output needed is as a nested dictionary:
{"pathConstraint" : {"latency" : {"latencyValue" : "low"}}}
推荐答案
您可以使用以下递归函数:
You could use the following recursive function:
def string_to_dict(keys, value):
key = keys.split('/')
if len(key) == 2:
return {key[1]: value}
else:
return string_to_dict('/'.join(key[:-1]), {key[-1]: value})
输出:
>>> string_to_dict(diff_str, value)
{'pathConstraint': {'latency': {'latencyValue': 'low'}}}
请注意,这假定 diff_str
以/
字符开头.
Note that this assumes that diff_str
begins with a /
character.
这篇关于将字符串转换为嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文