简体   繁体   中英

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!

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 .

You can use 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])}

Output:

{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM