python-3.x - 在 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)
有没有一种更简洁的方法可以做到这一点而无需弹出并创建一个新数组并直接在结果字典上执行此操作
解决方案
您可以使用列表理解:
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'}
推荐阅读
- couchbase - 如何按格式化的字符串字段分组?
- ios - 您如何找出在 SwiftUI 中点击了哪个视图?
- node.js - Javascript/Nodejs Promise 中的多次延迟
- python - 在 Jupyter Hub 中瞧瞧
- git - 使用 shell 脚本访问启用了 MFA 的 github
- python - 如何在 Python 上纠正井字游戏的 While 循环?
- php - WooCommerce 中特定产品变体的自定义后缀
- amazon-web-services - 如何连接到 AWS 中应用程序负载均衡器后面托管的应用程序?
- javascript - 如何获取 Instagram 用户的个人资料图片?
- swift - Objective c 中的测试字符串扩展