通过"."切分 dict 层级,"."个数不固定但不会超过 10 个
例子如下
# 转换前
{"a.b.c": "value1","a.b.d": "value2","a.x":"value3"}
# 转换后
{
"a":{
"b":{
"c":"value1",
"d":"value2"
}
}
"x":"value3"
}
遍历 dict,判断"."个数强行赋值可以实现,但是感觉太不优雅
请问下这种转换有啥简单的写法么
百度了下,找到个蛮简单的方法了
d2 = {}
def dotToDict(d1):
for key, value in d1.items():
if "." in key:
parts = key.split(".")
par = d2
key = parts.pop(0)
while parts:
par = par.setdefault(key, {})
key = parts.pop(0)
par[key] = value
else:
d2[key] = value
d = {"a.b.c": "value1","a.b.d": "value2","a.x": "value3"}
dotToDict(d)
print(d2)
#{'a': {'b': {'c': 'value1', 'd': 'value2'}, 'x': 'value3'}}
1
lau52y 2020-07-07 08:55:38 +08:00 via iPhone 1
|