Skip to main content
 首页 » 编程设计

python之展开嵌套的 Python 字典

2024年12月31日8yxwkf

什么是最干净的转换方式

{"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}]}}}