首页 > 解决方案 > 在 Python 3 中将列表转换为字典列表

问题描述

我在 Python 中有一本字典,如下所示:

result = {"name":"testipgroup",
          "ips": ["10.1.1.7","10.1.1.8"],
          "team_name": "avengers"}

我需要的输出是这种格式:

result = {"name":"testipgroup",
          "ips": [{"name":"IP_10.1.1.7", "value":"10.1.1.7"}],
          "team_name": "avengers"}

我的实现涉及从结果字典中弹出“ips”列表,遍历列表,进行转换,然后将新的字典列表附加到结果字典中,如下所示:

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)

有没有一种更简洁的方法可以做到这一点而无需弹出并创建一个新数组并直接在结果字典上执行此操作

标签: python-3.xlistdictionary

解决方案


您可以使用列表理解:

result['ips'] = [{'name': 'IP_' + i, 'value': i} for i in result['ips']]

result会成为:

{'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'}

推荐阅读