如何在设备无对应软件时为字典值数组补充Null值?
构建设备软件版本映射字典(缺失时填充None)
原始设备软件列表
[ [ {"name": "openjdk-8-jre", "version": "8u171-b11-1~deb9u1"}, {"name": "python2.7", "version": "2.7.13"}, {"name": "npm", "version": "8.0.0"}, ], [ {"name": "openjdk-8-jre", "version": "8u171-b11-1~deb9u1"}, ], [ {"name": "python2.7", "version": "2.7.13"}, {"name": "npm", "version": "7.0.0"}, ], ]
需求说明
需要构建一个字典,以软件名称为键,值为对应每台设备的版本数组:
- 若某设备安装了该软件,数组对应位置填版本号
- 若未安装,对应位置填充
None
尝试的代码
softwares = {} for software in all_equipment_softwares: softwares[software] = [] for equipment in equipments_dump: for software in equipment["softwares"]: software_name = software["name"] software_version = software["version"] softwares[software_name].append(software_version)
当前错误结果
[ {"openjdk-8-jre": ["8u171-b11-1~deb9u1", "8u171-b11-1~deb9u1"]}, {"python2.7": ["2.7.13", "2.7.13"]}, {"npm": ["8.0.0", "7.0.0"]}, ]
预期结果
[ {"openjdk-8-jre": ["8u171-b11-1~deb9u1", "8u171-b11-1~deb9u1", None]}, {"python2.7": ["2.7.13", None, "2.7.13"]}, {"npm": ["8.0.0", None, "7.0.0"]}, ]
解决方案
问题出在你仅遍历了设备已安装的软件来追加版本,未处理未安装的情况。正确思路是:
- 先收集所有唯一的软件名称,初始化每个软件的版本数组
- 遍历每一台设备,对每个软件名称:
- 检查当前设备是否安装了该软件,有则取版本号,无则填
None - 将值追加到对应软件的数组中
- 检查当前设备是否安装了该软件,有则取版本号,无则填
修正后的代码
# 假设原始设备软件列表为equipment_softwares_list equipment_softwares_list = [ [ {"name": "openjdk-8-jre", "version": "8u171-b11-1~deb9u1"}, {"name": "python2.7", "version": "2.7.13"}, {"name": "npm", "version": "8.0.0"}, ], [ {"name": "openjdk-8-jre", "version": "8u171-b11-1~deb9u1"}, ], [ {"name": "python2.7", "version": "2.7.13"}, {"name": "npm", "version": "7.0.0"}, ], ] # 1. 收集所有唯一的软件名称 all_software_names = set() for equip_softwares in equipment_softwares_list: for sw in equip_softwares: all_software_names.add(sw["name"]) all_software_names = list(all_software_names) # 2. 初始化结果字典,每个软件对应空数组 result = {sw: [] for sw in all_software_names} # 3. 遍历每台设备,填充每个软件的版本/None for equip_softwares in equipment_softwares_list: # 将当前设备的软件转成{名称:版本}字典,快速查找 equip_sw_dict = {sw["name"]: sw["version"] for sw in equip_softwares} # 对每个软件,检查是否存在于当前设备 for sw_name in all_software_names: result[sw_name].append(equip_sw_dict.get(sw_name, None)) # 转换为预期的列表格式 output = [{k: v} for k, v in result.items()] print(output)
代码解释
- 用集合收集唯一软件名,避免重复
- 遍历设备时先转成字典,将查找操作的时间复杂度降到O(1),提升效率
- 用
dict.get()方法:存在则取版本号,不存在则返回None,直接追加到对应数组
运行后即可得到符合预期的结果。
内容的提问来源于stack exchange,提问作者Bugui
相关产品推荐
相关产品推荐

