Python 创建具有多个不同大小列表的嵌套字典

Python 创建具有多个不同大小列表的嵌套字典,python,list,dictionary,nested,Python,List,Dictionary,Nested,我有这4张清单。目标是获取嵌套字典?有了这段代码,我就有了想要的结果,但我想知道是否有更多的pythonic方法可以做到这一点 import pprint weights = ["weights"] weights_values =[1.0, 0.0, 0.234, 1.0, 0.5 , 1.0, 0.0 ,0.9] indices = [0, 1, 2, 3] joint_names = ["joint1", "joint2"]

我有这4张清单。目标是获取嵌套字典?有了这段代码,我就有了想要的结果,但我想知道是否有更多的pythonic方法可以做到这一点

import pprint
weights = ["weights"]
weights_values =[1.0, 0.0, 0.234, 1.0, 0.5 , 1.0, 0.0 ,0.9]
indices = [0, 1, 2, 3]
joint_names = ["joint1", "joint2"]


counter = 0
temp_joint_dict = dict()
temp_weights_dict = dict()
weights_dict = dict()
for x in weights:
    for i, w in zip(indices*len(indices), weights_values):
        temp_weights_dict[i] = w
        if len(temp_weights_dict) == len(indices):
            temp_joint_dict[joint_names[counter]] = temp_weights_dict
            temp_weights_dict = dict()
            counter += 1
    weights_dict[x] = temp_joint_dict

pprint.pprint(weights_dict)

这可以通过列表扩展显著缩短:

weights = {}
weights["weights"] = dict(zip(joint_names, [{n: x for n, x in enumerate(weights_values[i:i + len(indices)])} for i in range(0, len(weights_values), len(indices))] ))
结果:

{'weights': {'joint1': {0: 1.0, 1: 0.0, 2: 0.234, 3: 1.0}, 'joint2': {0: 0.5, 1: 1.0, 2: 0.0, 3: 0.9}}}

关于代码优雅性和习惯用法的问题,特别是当它是一个需要改进的一般性问题时,更适合于。他们不支持从这里迁移问题;在发布之前,一定要阅读他们的常见问题解答等。也就是说:看起来你的任务真的是,从每个块中制作一个dict(
[dict(enumerate(chunk))for chunk in chunk]
),然后将它们用作指定键名的值(
dict(zip(keys,values))
。我已经在这里得到了答案。我要删除这个帖子吗?@iRex我对此很矛盾。我将投票结束这个问题,但如果有一个经过投票并被接受的答案,不删除它可能有价值。这取决于你,因为这是你的问题,你可以删除它。