嵌套字典理解 - 字典的字典

nested dictionary comprehension - dictionary of dictionaries

如何通过字典推导得到需要的输出?

{'R': {0: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
   1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
   2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
   3: {2: 0, 3: 0, 4: 0, 5: 0, 1: 0}},
 'L': {0: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
   1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
   2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
   3: {2: 0, 3: 0, 4: 0, 5: 0, 1: 0}},
 'B': {0: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
   1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
   2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
   3: {2: 0, 3: 0, 4: 0, 5: 0, 1: 0}}}

我是通过下面的代码得到的:

d_clas = {'B':{} , 'C':{}, 'D':{}}
l_uniq = [array([1, 2, 3, 4, 5], dtype=int64),
      array([1, 2, 3, 4, 5], dtype=int64),
      array([1, 2, 3, 4, 5], dtype=int64),
      array([2, 3, 4, 5, 1], dtype=int64)]

for i in d_clas:
    c_clas = {}
    for j in range(len(l_uniq)-1):
        c_clas[j] = {}
        for k in l_uniq[j]:
        c_clas[j][k] = 0
    d_clas[i] = c_clas

慢慢开始。我喜欢从最里面的项目开始,然后向外工作。

您开始于:

d_clas = {'B':{} , 'C':{}, 'D':{}}
for i in d_clas:
    c_clas = {}
    for j in range(len(l_uniq)-1):
        c_clas[j] = {}
        for k in l_uniq[j]:
            c_clas[j][k] = 0
    d_clas[i] = c_clas

先做最里面的结构:

d_clas = {'B':{} , 'C':{}, 'D':{}}
for i in d_clas:
    c_clas = {}
    for j in range(len(l_uniq)-1):
        c_clas[j] = {k: 0 for k in l_uniq[j]}
    d_clas[i] = c_clas

那么下一个:

d_clas = {'B':{} , 'C':{}, 'D':{}}
for i in d_clas:
    d_clas[i] = {
        j: {k: 0 for k in l_uniq[j]} 
        for j in range(len(l_uniq) - 1)
    }

最后一个结构:

d_clas = {
    i: {
        j: {k: 0 for k in l_uniq[j]} 
        for j in range(len(l_uniq) - 1)
    }
    for i in ('B', 'C', 'D')
}