由于键是散列的 - 字符串键中是否存在点以及尝试访问没有语义意义root["a"]["c"]
会导致TypeError
如前所述,例外。
但是,您可以重新构造字典以具有您正在寻找的嵌套结构。
代码大致如下:
root = {
"a": 0.7615894039735099,
"a.b": 0.7152317880794702,
"a.c": 0.026490066225165563,
"a.b.d": 0.0001,
"f": 0.002,
"f.g": 0.00003,
"h.p.q": 0.0004
}
result = {}
for key, value in root.items():
if not isinstance(key, str):
result[key] = value
is_nested = "." in key
nesting_clash = any([k.startswith(key) for k in root if k != key])
if nesting_clash:
print(f"key {key} has nesting clash ; replacing with {key}._v")
# continue # fixed after comment
key = f"{key}._v"
is_nested = True
if not is_nested:
result[key] = value
key_parts = key.split(".")
tmp = result
for idx, key_part in enumerate(key_parts):
default_value = {} if idx < len(key_parts) - 1 else value
tmp[key_part] = tmp.get(key_part, default_value)
tmp = tmp[key_part]
注意:您必须丢弃冲突的键(例如"a"
and "a.b"
)或为它们创建默认行为。在我的例子中,我决定放弃它们。
编辑:我已经用 ._v 的关键替换替换了跳过。这样你就可以保留所有值并使用以下函数重建原始字典/JSON:
def unnest_dict(d, sep="."):
result = {}
for key, val in d.items():
if not isinstance(val, dict):
result[key] = val
continue
if "_v" in val:
result[key] = val.pop("_v")
unnested_val = unnest_dict(val, sep)
for k, v in unnested_val.items():
result[sep.join([key, k])] = v
return result