I have a little bit of a logic game. I have list with following dicts in each listnode.
{1: [1,{'X': -0.48595, 'Y': 0.0, 'Z': 0.56283},
2,{'X': -0.48595, 'Y': 0.0, 'Z': -0.6}],
2: [2,{'X': -0.48595, 'Y': 0.0, 'Z': -0.6},
4,{'X': 1.14756, 'Y': 0.0, 'Z': -0.6}],
3: [4,{'X': 1.14756, 'Y': 0.0, 'Z': -0.6},
9,{'X': 1.14756, 'Y': 0.0, 'Z': 0.8}]}
What I want? List with nodes of lists as below:
[{'Id': 1, 'Nodes': [{'Id': 1, 'Position': {'X': -0.48595, 'Y': 0.0, 'Z': 0.56283}},
{'Id': 2, 'Position': {'X': -0.48595, 'Y': 0.0, 'Z': -0.6}}]},
{'Id': 2, 'Nodes': [{'Id': 2, 'Position': {'X': -0.48595, 'Y': 0.0, 'Z': -0.6}},
{'Id': 4, 'Position': {'X': 1.14756, 'Y': 0.0, 'Z': -0.6}}]},
{'Id': 3, 'Nodes': [{'Id': 4, 'Position': {'X': 1.14756, 'Y': 0.0, 'Z': -0.6}},
{'Id': 9, 'Position': {'X': 1.14756, 'Y': 0.0, 'Z': 0.8}}]}]
How can I make that transformation? I'm keep trying modifying my code, but everytime something's wrong.
mem_list = []
for x in range(len(list_temp)):
mem_loc_list = []
for key in list_temp[x]:
nodes_list = []
member = {}
member['Id'] = key
node_dict = {}
for y in list_temp[x][key]:
if type(y) == int:
node_dict['Id'] = y
else:
node_dict['Position'] = y
nodes_list.append(node_dict)
member['Nodes'] = nodes_list
mem_loc_list.append(member)
CodePudding user response:
Using list comprehension you can do it like this:
[[{"Id": k, "Nodes": [{"Id": v[i], "Position": v[i 1]} for i in range(0, len(v), 2)]}
for k,v in data.items()] for data in list_temp]