Python:从键:值对字符串创建嵌套字典

标签 python list dictionary multidimensional-array

我有一个这样的字典:

{"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, {})

我无法在这里完成部分代码。也许我需要用我的描述性语言进行更好的设计。欢迎提出任何建议。

最佳答案

您可以将itertools.groupby与递归一起使用:

import re, itertools
d = {"key1:key2[0]:key3": "1234", "key1:key2[0]:key4": "4567", "key1:key2[1]:key3": "789", "key1:key2[1]:key4": "12345"}
new_d = [(re.findall('\w+', a), b) for a, b in d.items()]
def last_group(d):
  return [{a[-1]:c for a, c in list(b)} for _, b in itertools.groupby(sorted(d, key=lambda x:x[0][1]), key=lambda x:x[0][1])]

def group_data(d):
   return {a:(lambda x:group_data([(c[1:], d) for c, d in x]) if all(len(c) > 3 for c, _ in x) else last_group(x))(list(b)) for a, b in itertools.groupby(sorted(d, key=lambda x:x[0][0]), key=lambda x:x[0][0])}

print(group_data(new_d))

输出:

{'key1': {'key2': [{'key3': '1234', 'key4': '4567'}, {'key3': '789', 'key4': '12345'}]}}

关于Python:从键:值对字符串创建嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50100690/

相关文章:

python - Django:为什么当我在 django 中通过 popen 使用 Ghostscript 时,会出现 "file not found"错误

c# - 如何重构此 if 语句以添加或更新字典?

java - 如何将列表/ map 与组合框一起使用

scala - 替换列表元素中的字符串

python - Pandas 数据框的列表列表

javascript - 使用 Leaflet 和 AngularJS 的热图

python - Geopy异常处理

python - def 语句创建一个新列 - pandas

python - 对列表的单个元素进行排序

c - 从函数导出列表