嵌套列表到嵌套的dict python3

MLa*_*Lam 2 python dictionary list

我有一个列表如下:

L = [[0,[1,1.0]],
     [0,[2,0.5]],
     [1,[3,3.0]],
     [2,[1,0.33],
     [2,[4,1.5]]]
Run Code Online (Sandbox Code Playgroud)

我想将它转换为嵌套的dict,如下所示:

D = {0:{1: 1.0,
        2: 0.5},
     1:{3: 3.0},
     2:{1: 0.33,
        4: 1.5}
     }
Run Code Online (Sandbox Code Playgroud)

我不确定如何转换它.有什么建议吗?谢谢!

Rec*_*eck 7

初学者友好,

D = {}
for i, _list in L:
    if i not in D:
        D[i] = {_list[0] : _list[1]}
    else:
        D[i][_list[0]] = _list[1]})
Run Code Online (Sandbox Code Playgroud)

结果:

{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
Run Code Online (Sandbox Code Playgroud)


Rom*_*est 6

随着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))
Run Code Online (Sandbox Code Playgroud)

输出:

{0: {1: 1.0, 2: 0.5}, 1: {3: 3.0}, 2: {1: 0.33, 4: 1.5}}
Run Code Online (Sandbox Code Playgroud)
  • collections.defaultdict(dict)- 第一个参数提供default_factory属性的初始值; 它默认为None.设置default_factoryto dict使得defaultdict构建字典字典非常有用.

  • 在L:`中使用`for k,(k2,v) (3认同)