Convert a list to list of dictionaries in Python 3

Amistad

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

blhsing

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.

edited at
0

Comments

0 comments
Login to comment

Related

Convert list to list of dictionaries: Python

Convert XML to List of Dictionaries in python

Convert list of dictionaries to EXCEL with Python

convert string to list of dictionaries in python

Convert list of dictionaries into dataframe python

Convert csv into list of dictionaries in python

Python: convert list of dictionaries into dataframe

How convert list of dictionaries to a dictionary of dictionaries in Python

Python: Convert list of dictionaries to list of lists

Convert string to list within list of dictionaries in python

How to convert a list of strings to list of dictionaries in python?

Python dict comprehension convert list of tuples of dictionaries and integers into list of dictionaries

Sorting a list of dictionaries in Python 3

List of Dictionaries Python3

Convert a list of dictionaries into a set of dictionaries

Python - Convert List Of Dictionaries & Key Values To String

Convert pandas.DataFrame to list of dictionaries in Python

How to convert a list of dictionaries to JSON in Python / Django?

How to convert a list of tuples to a dictionary of dictionaries in Python?

Python - Convert recursively to string in list of dictionaries

Convert pyspark dataframe into list of python dictionaries

convert seconds in list of dictionaries into hours, python

Python - How to convert a list of dictionaries with tree items?

How to convert CSV file into a list of dictionaries in python

Convert python list of dictionaries to dataframe in pandas

Python: Convert a list of dictionaries into a JSON object

Python List to List of Dictionaries

Convert a file to a list of dictionaries

Convert a string to list of dictionaries