2

I have some lists defined as the following :

main_0 = ['Main_0']
main_1 = ['Main_1']
main_2 = ['Main_2']

level_0 = ['LEVEL0',
           'LEVEL0_1',
           'LEVEL0_2']
level_1 = ['LEVEL1',
           'LEVEL1_1']
level_2 = ['LEVEL2']

val_0 = [1, 2, 3]
val_1 = [10, 20]
val_2 = [52]

And I want to create a nested dictionary like the following:

{'Main_0' : {'LEVEL0' : 1,
             'LEVEL0_1' : 2,
             'LEVEL0_2' : 3},
 'Main_1' : {'LEVEL1' : 10,
             'LEVEL1_1' : 20},
 'Main_2' : {'LEVEL2' : 52}}

Is that even possible or should I tackle this problem with a different data structure? Which one in that case?

0

2 Answers 2

3

You can use dict comprehension in multiple levels:

In [195]: mains = [main_0, main_1, main_2]

In [196]: levels = [level_0, level_1, level_2]

In [197]: vals = [val_0, val_1, val_2]

In [200]: {m[0]: {l: v for l, v in zip(ll, vv) } for m, ll, vv in zip(mains, lev
     ...: els, vals)}
Out[200]: 
{'Main_0': {'LEVEL0': 1, 'LEVEL0_1': 2, 'LEVEL0_2': 3},
 'Main_1': {'LEVEL1': 10, 'LEVEL1_1': 20},
 'Main_2': {'LEVEL2': 52}}
Sign up to request clarification or add additional context in comments.

2 Comments

Was going to post the exact same solution; {m[0]: {l: v for l, v in zip(levels[i], vals[i])} for i, m in enumerate(mains)}. Guess using another zip is the better solution.
The inner dict comprehension can be replaced with dict(zip(ll, vv)).
1

Just iterate over each of these lists and build a hash:

mains = main_0 + main_1 + main_2
levels = [level_0, level_1, level_2]
values = [val_0, val_1, val_2]

result = {}
for main_index, main in enumerate(mains):
    level_result = {}
    for level_index, level in enumerate(levels[main_index]):
        value = values[main_index][level_index]
        level_result[level] = value
    result[main] = level_result

print(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.