gpt4 book ai didi

python - 来自多个列表的嵌套字典与 python

转载 作者:行者123 更新时间:2023-11-28 22:18:49 25 4
gpt4 key购买 nike

我有一些列表定义如下:

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

这是否可能或者我应该使用不同的数据结构来解决这个问题?在那种情况下是哪一个?

最佳答案

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

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

关于python - 来自多个列表的嵌套字典与 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50228146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com