![](/img/trans.png)
[英]Python3: Converting a nested dict into a list of objects with “children” and “leaf”?
[英]nested list to nested dict python3
我有一個列表如下:
L = [[0,[1,1.0]],
[0,[2,0.5]],
[1,[3,3.0]],
[2,[1,0.33],
[2,[4,1.5]]]
我想將其轉換為嵌套的字典,如下所示:
D = {0:{1: 1.0,
2: 0.5},
1:{3: 3.0},
2:{1: 0.33,
4: 1.5}
}
我不確定如何轉換它。 有什么建議嗎? 謝謝!
初學者友好,
D = {}
for i, _list in L:
if i not in D:
D[i] = {_list[0] : _list[1]}
else:
D[i][_list[0]] = _list[1]})
結果:
{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
使用collections.defaultdict([default_factory[, ...]])
類:
import collections
L = [[0,[1,1.0]],
[0,[2,0.5]],
[1,[3,3.0]],
[2,[1,0.33]],
[2,[4,1.5]]]
d = collections.defaultdict(dict)
for k, (sub_k, v) in L:
d[k][sub_k] = v
print(dict(d))
輸出:
{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
collections.defaultdict(dict)
- 第一個參數提供default_factory
屬性的初始值; 它默認為None
。 將default_factory
設置為dict
使得defaultdict
可用於構建字典字典。您可以使用itertools.groupby
:
import itertools
L = [[0,[1,1.0]],
[0,[2,0.5]],
[1,[3,3.0]],
[2,[1,0.33]],
[2,[4,1.5]]
]
new_l = {a:dict([i[-1] for i in b]) for a, b in itertools.groupby(L, key=lambda x:x[0])}
輸出:
{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.