Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested list to nested dict python3

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!

like image 745
MLam Avatar asked Dec 03 '25 09:12

MLam


2 Answers

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}}
like image 124
Reck Avatar answered Dec 04 '25 22:12

Reck


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.
like image 44
RomanPerekhrest Avatar answered Dec 04 '25 22:12

RomanPerekhrest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!