我有一个字典:a = { "group_a/category_a/metric_a": 5, "group_a/category_a/metric_b": 4, "group_a/category_b/metric_a": 3, "group_a/category_b/metric_b": 2, "group_b/category_a/metric_d": 1}我想通过创建一个由每个斜杠分隔的嵌套视图来解压节点,结果如下所示:b = { "group_a": { "category_a": { "metric_a": 5, "metric_b": 4 }, "category_b": { "metric_a": 3, "metric_b": 2 }, "group_b": { "category_a": { "metric_d": 1 } }}我们怎样才能从a到b呢?我在尝试将上面的字典发布到 Firebase 时遇到了这个问题,因为节点group_a/category_a/metric_a不被接受,而嵌套的字典是允许的。
1 回答
慕哥9229398
TA贡献1877条经验 获得超6个赞
循环遍历,将每个键拆分为键列表,根据需要创建子字典......
from pprint import pprint
a = {
"group_a/category_a/metric_a": 5,
"group_a/category_a/metric_b": 4,
"group_a/category_b/metric_a": 3,
"group_a/category_b/metric_b": 2,
"group_b/category_a/metric_d": 1
}
b = {}
for k, v in a.items():
dct = b
keys = k.split("/")
for key in keys[:-1]:
if key not in dct:
dct[key] = {}
dct = dct[key]
dct[keys[-1]] = v
pprint(b)
给出:
{'group_a': {'category_a': {'metric_a': 5, 'metric_b': 4},
'category_b': {'metric_a': 3, 'metric_b': 2}},
'group_b': {'category_a': {'metric_d': 1}}}
添加回答
举报
0/150
提交
取消