Home > Blockchain >  Dict within a dict
Dict within a dict

Time:03-29

I have the following data structure and written code:

alpha = {'Jan': [1,2,3]}
beta = {'Jan': [4,5,6]}
carter = {'Jan': ['boo', 'fee', 'lee']}

delta = {month: {month: [b-a for (b, a) in zip(be, al)]
                for (month, be), (month, al) in zip(beta.items(), alpha.items())}
        for month, ca in carter.items()}

print(delta)
{'Jan': {'Jan': [3, 3, 3]}}

However, I want the result to look like this:

{'Jan': {'boo': 3, 'fee': 3, 'lee': 3}

what is the right way to write this to get desired result?

CodePudding user response:

Assuming you meant your output as {'Jan': {'boo': 3, 'fee': 3, 'lee': 3}}:

delta = {month: 
            {ca : (b - a) for ca, b, a in zip(carter[month], beta[month], alpha[month])} 
            for month in carter.keys()}

CodePudding user response:

A simple dictionary comprehension should help:

alpha = {'Jan': [1,2,3]}
beta = {'Jan': [4,5,6]}
carter = {'Jan': ['boo', 'fee', 'lee']}
K = list(alpha)[0]
delta = {K: {n: a - b for n, a, b in zip(Carter[K], beta[K], alpha[K])}}
print(delta)

Output:

{'Jan': {'boo': 3, 'fee': 3, 'lee': 3}}
  • Related