Search code examples
pythondictionarydictionary-comprehension

nested dictionary comprehension - dictionary of dictionaries


How shall I achieve the required output through dictionary comprehensions?

{'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}}}

I got it through the code below:

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

Solution

  • Start slow work your way up. I like to start with the inner most item and work outwards.

    You started with:

    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
    

    First do the inner most structure:

    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
    

    Then the next one:

    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)
        }
    

    Finally the last structure:

    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')
    }