Home > Software engineering >  What is a clean way to map a template without to know the total items
What is a clean way to map a template without to know the total items

Time:09-22

In this example I have 2 items in the data list and want parse template with each items and generate a result:

template = [  {"id": "<ID>", "interfaces": [{"port": "<PORT>", "description": "<NAME>"}]} ]

data = [  {'id': '1234', 'port': 'ETH0', "description": "MyDescName"},
          {'id': '4567', 'port': 'ETH1', "description": "MyDescName-2"} ]

result  = [  {"id": "1234", "interfaces": [{"port": "ETH0", "description": "MyDescName"}]},
             {"id": "4567", "interfaces": [{"port": "ETH1", "description": "MyDescName-2"}] ]

CodePudding user response:

data = [  
        {'id': '1234', 'port': 'ETH0', "description": "MyDescName"},
        {'id': '4567', 'port': 'ETH1', "description": "MyDescName-2"},
       ]
                 
result = []

for element in data:
  result.append({"id": element["id"], "interfaces": [{"port": element["port"], "description": element["description"]}]})

print(result)

This one liner works too.

result2 = list(map(lambda element: {"id": element["id"], "interfaces": [{"port": element["port"], "description": element["description"]}]}, data))

Gives output

[
 {'id': '1234', 'interfaces': [{'port': 'ETH0', 'description': 'MyDescName'}]}, 
 {'id': '4567', 'interfaces': [{'port': 'ETH1', 'description': 'MyDescName-2'}]}
]
  • Related