python - 展开嵌套的 Python 字典

标签 python list dictionary

什么是最干净的转换方式

{"a.b.c[0].key1": 1, "a.b.c[1].key2": 2, "a.b.c[3].key3": 3}

进入这个

{"a": {"b": {"c": [{"key1": 1}, {"key2": 2}, None, {"key3": 3}]}}}
  • 字典键可以是任何东西。
  • 列表的长度可能会有所不同。
  • 字典的深度可能会有所不同。
  • 如果列表中有缺失值,则该值必须为 None。
  • 如果值重复,最后声明的值才算数。

我想到了以下工作示例。

想知道我们是否可以为我们的社区找到更好的解决方案。

def unflatten(data):
    if type(data) != dict:
        return None
    regex = r'\.?([^.\[\]]+)|\[(\d+)\]'
    result_holder = {}
    for key,value in data.items():
        cur = result_holder
        prop = ""
        results = re.findall(regex, key)
        for result in results:
            prop = int(prop) if type(cur) == list else prop
            if (type(cur) == dict and cur.get(prop)) or (type(cur) == list and len(cur) > prop):
                cur = cur[prop]
            else:
                if type(cur) == list:
                    if type(prop) is int:
                        while len(cur) <= prop:
                            cur.append(None)
                cur[prop] = list() if result[1] else dict()
                cur = cur[prop]
            prop = result[1] or result[0]

        prop = int(prop) if type(cur) == list else prop

        if type(cur) == list:
            if type(prop) is int:
                while len(cur) <= prop:
                    cur.append(None)

        print(len(cur), prop)
        cur[prop] = data[key]

    return result_holder[""] or result_holder

最佳答案

你可以使用递归:

d = {"a.b.c[0].key1": 1, "a.b.c[1].key2": 2, "a.b.c[3].key3": 3}
from itertools import groupby
import re
def group_data(data):
  new_results = [[a, [i[1:] for i in b]] for a, b in groupby(sorted(data, key=lambda x:x[0]), key=lambda x:x[0])]
  arrays = [[a, list(b)] for a, b in groupby(sorted(new_results, key=lambda x:x[0].endswith(']')), key=lambda x:x[0].endswith(']'))]
  final_result = {}
  for a, b in arrays:
     if a:
       _chars = [[c, list(d)] for c, d in groupby(sorted(b, key=lambda x:re.findall('^\w+', x[0])[0]), key=lambda x:re.findall('^\w+', x[0])[0])]
       _key = _chars[0][0]
       final_result[_key] = [[int(re.findall('\d+', c)[0]), d[0]] for c, d in _chars[0][-1]]
       _d = dict(final_result[_key])
       final_result[_key] = [group_data([_d[i]]) if i in _d else None for i in range(min(_d), max(_d)+1)]
     else:
        for c, d in b:
           final_result[c] = group_data(d) if all(len(i) >1 for i in d) else d[0][0]
  return final_result

print(group_data([[*a.split('.'), b] for a, b in d.items()]))

输出:

{'a': {'b': {'c': [{'key1': 1}, {'key2': 2}, None, {'key3': 3}]}}}

关于python - 展开嵌套的 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52373266/

相关文章:

python:查找围绕某个 GPS 位置的圆的 GPS 坐标的优雅方法

string - 在二维矩阵中排列 3 个字母的单词,使得每一行、每一列和对角线形成一个单词

Python 读取大型文本文件(几 GB)的最快方法

python - 使用 brew 安装 Pyqt4

python - AppEngine 警告 - OpenBLAS 警告 - 无法确定此系统上的 L2 缓存大小

python - 为列表生成器结果分配不同的值

python - 将列表的每个元素作为函数的参数发送

list - 在 lisp 中左右旋转列表的 n 个元素的递归函数

python - PyYaml.load_all() 返回生成器而不是字典?

python - 如何正确排序带有数字的字符串?