I have a list as below:
L = [[0,[1,1.0]],
[0,[2,0.5]],
[1,[3,3.0]],
[2,[1,0.33],
[2,[4,1.5]]]
I would like to convert it into a nested dict as below:
D = {0:{1: 1.0,
2: 0.5},
1:{3: 3.0},
2:{1: 0.33,
4: 1.5}
}
I'm not sure how to convert it. Any suggestion? Thank you!
Beginners friendly,
D = {}
for i, _list in L:
if i not in D:
D[i] = {_list[0] : _list[1]}
else:
D[i][_list[0]] = _list[1]})
Result:
{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
With collections.defaultdict([default_factory[, ...]]) class:
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))
The output:
{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
collections.defaultdict(dict) - the first argument provides the initial value for the default_factory attribute; it defaults to None.
Setting the default_factory to dict makes the defaultdict useful for building a dictionary of dictionaries.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With