I have a dictionary in Python as follows:
result = {"name":"testipgroup",
"ips": ["10.1.1.7","10.1.1.8"],
"team_name": "avengers"}
The output I need is in this format :
result = {"name":"testipgroup",
"ips": [{"name":"IP_10.1.1.7", "value":"10.1.1.7"}],
"team_name": "avengers"}
My implementation involves popping the 'ips' list from the result dict, iterating over the list, doing transformations and then appending the new list of dicts to the result dict as follows:
a = result.pop("ips")
result["ips"] = []
for item in a:
ip_dict = {}
ip_dict.update({"name": "IP_" + str(item), "value": str(item)})
result["ips"].append(ip_dict)
Is there a cleaner way of doing this without popping and creating a new array and doing this directly on the result dict
You can use list comprehension:
result['ips'] = [{'name': 'IP_' + i, 'value': i} for i in result['ips']]
result
would become:
{'name': 'testipgroup', 'ips': [{'name': 'IP_10.1.1.7', 'value': '10.1.1.7'}, {'name': 'IP_10.1.1.8', 'value': '10.1.1.8'}], 'team_name': 'avengers'}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments