简体   繁体   中英

How to transform this dict output?

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)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM