-1

I have this 4 lists. The goal is to get nested dictionary? With this code I have desired result but I would like to know If there is more pythonic way of do this.

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)
IKA
  • 151
  • 1
  • 3
  • 11
  • 1
    Questions about code elegance and idiom, especially when it's a generic call for improvements, are a better fit for https://codereview.stackexchange.com. They don't support question migration from here; be sure to read their FAQ etc. before posting. – Karl Knechtel Apr 04 '21 at 20:46
  • 2
    That said: it seems like your task is really to [split the `weights_values` into equally sized chunks](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks), make a dict from each chunk (`[dict(enumerate(chunk)) for chunk in chunks]`), and then use those as the values for specified key names (`dict(zip(keys, values))`). – Karl Knechtel Apr 04 '21 at 20:51
  • I already got my answer here. Shall I delete this thread? – IKA Apr 05 '21 at 08:20
  • @iRex I'm ambivalent about it. I'll vote to close the question, but with an upvoted and accepted answer, there may be value in not deleting it. It's up to you, since it's your question, you can delete it. – joanis Apr 05 '21 at 11:24

1 Answers1

1

This can be shortened significantly with list comperhension:

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))] ))

Result:

{'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}}}
RJ Adriaansen
  • 9,131
  • 2
  • 12
  • 26