【发布时间】:2018-04-30 12:35:42
【问题描述】:
我有一个这样的字典:
{"key1:key2[0]:key3[0]": "1234",
"key1:key2[0]:key4[0]:key5": "4567",
"key1:key2[1]:key3[0]": "789",
"key1:key2[1]:key4[1]:key5": "12345"}
键是表示目标字典中每个最终值的沿袭的描述性方式。 : 将父键与其子键分开,[] 表示前键的值是一个列表,并且索引存在于大括号之间。
鉴于此,我该如何构造一个像
{
"key1":{
"key2":[
{
"key3":["1234"],
"key4":[{"key5":"4567"}]
},
{
"key3":["789"],
"key4":[{"key5":"12345"}]
}
]
}
}
我试图做这样的事情:
result_dict = {}
def populate(target_path, value):
current_point_in_path = None
t = result_dict
target_path = target_path.split(":")
for i, each_key in enumerate(target_path):
list_index = re.findall(r'\[(.*?)\]', each_key)
if len(list_index) > 1:
raise Exception("not allowed")
elif len(list_index) == 1:
index = int(list_index[0])
key_before = each_key.split(index)[0]
if not isinstance(result_dict[key_before], list):
t = t.setdefault(key_before, [])
if i+1 == len(target_path):
# the issue is that this insert won't return a pointer to the current index element like setdefault would do
# alternate soultions are wc
t.insert(index, value)
else:
t.insert(index, {})
else:
if i + 1 == len(target_path):
t = t.setdefault(each_key, value)
else:
t = t.setdefault(each_key, {})
我无法在这里完成部分代码。也许我需要用我的描述性语言进行更好的设计。欢迎提出任何建议。
【问题讨论】:
-
“也许我需要用我的描述性语言进行更好的设计。欢迎提出任何建议。”源字典的数据从哪里来?因为如果可以的话,我建议你使用 JSON 标准来存储这种多级数据结构。 docs.python.org/2/library/json.html 使用 JSON,很容易转储(序列化)和加载(反序列化)这样的结构。
-
所以我的意思是,如果您可以将输入数据结构更改为另一种结构,我建议您使用 JSON。那么将JSON字符串的“解码”部分变成多级字典就很简单了:json.loads(json_string)! :)
标签: python list dictionary multidimensional-array