来自几个python列表的嵌套字典

时间:2018-05-08 07:27:00

标签: python python-3.x dictionary nested

我有一些列表定义如下:

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]

我想创建一个嵌套字典,如下所示:

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

这是可能的,还是应该用不同的数据结构解决这个问题?在那种情况下哪一个?

2 个答案:

答案 0 :(得分:3)

您可以在多个级别使用dict理解:

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

答案 1 :(得分:1)

只需遍历每个列表并构建一个哈希:

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)