Python 3.x 在Python3中将列表转换为字典列表
我有一本Python字典,如下所示:Python 3.x 在Python3中将列表转换为字典列表,python-3.x,list,dictionary,Python 3.x,List,Dictionary,我有一本Python字典,如下所示: result = {"name":"testipgroup", "ips": ["10.1.1.7","10.1.1.8"], "team_name": "avengers"} a = result.pop("ips") result["ips"] = [] for item in a: ip_dict = {} ip_dict.update({"name": "IP_" + str(item), "
result = {"name":"testipgroup",
"ips": ["10.1.1.7","10.1.1.8"],
"team_name": "avengers"}
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)
我需要的输出格式如下:
result = {"name":"testipgroup",
"ips": [{"name":"IP_10.1.1.7", "value":"10.1.1.7"}],
"team_name": "avengers"}
我的实现包括从结果dict弹出“ips”列表,在列表上迭代,进行转换,然后将新的dict列表附加到结果dict,如下所示:
result = {"name":"testipgroup",
"ips": ["10.1.1.7","10.1.1.8"],
"team_name": "avengers"}
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)
是否有一种更干净的方法来执行此操作,而无需弹出并创建新数组,并直接在结果上执行此操作dict您可以使用列表理解:
result['ips'] = [{'name': 'IP_' + i, 'value': i} for i in result['ips']]
结果将变成:
{'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'}
您可以使用列表理解:
result['ips'] = [{'name': 'IP_' + i, 'value': i} for i in result['ips']]
结果将变成:
{'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'}
看起来你只是想映射列表并将其包装在字典中,对其进行一些调整?如果是这样,为什么不尝试使用列表理解
result['ips'] = [{ 'name':'IP_' + ip, 'value': ip } for ip in result['ips']]
看起来你只是想映射列表并将其包装在字典中,对其进行一些调整?如果是这样,为什么不尝试使用列表理解
result['ips'] = [{ 'name':'IP_' + ip, 'value': ip } for ip in result['ips']]
这和@Blxing给出的答案有什么区别?@Onyanbu没有区别。我当时正在打字,但他/她先提交了。这和@Blxing给出的答案有什么区别?@Onyanbu没有区别。我当时正在打字,但他/她先提交了。