如何高效对特定格式的字典执行多次修改,实现键值映射转换?
Python 批量转换字典格式实现方案
核心逻辑是提取每个原始字典中Key字段的值作为新字典的键,Value字段的值作为新字典的值,具体实现如下:
单条字典转换
original_dict = {'Key': 'Name', 'Value': 'VOL-18fd3f81-b69e-47a8-8759-3e04abac962d'} converted_dict = {original_dict['Key']: original_dict['Value']} # 输出结果:{'Name': 'VOL-18fd3f81-b69e-47a8-8759-3e04abac962d'}
批量处理(最高效方案)
如果待处理的同格式字典存储在列表中,直接用推导式实现,时间复杂度为O(n),性能最优:
# 示例待处理字典列表 original_list = [ {'Key': 'Name', 'Value': 'VOL-18fd3f81-b69e-47a8-8759-3e04abac962d'}, {'Key': 'Status', 'Value': 'Running'}, {'Key': 'CreateTime', 'Value': '2024-05-20'} ] # 方案1:转换为独立字典组成的列表 converted_list = [{item['Key']: item['Value']} for item in original_list] # 方案2:合并为单个大字典(绝大多数场景常用) merged_dict = {item['Key']: item['Value'] for item in original_list} # merged_dict输出结果:{'Name': 'VOL-18fd3f81-b69e-47a8-8759-3e04abac962d', 'Status': 'Running', 'CreateTime': '2024-05-20'}
异常兼容处理
如果存在部分原始字典缺失Key或Value字段的情况,增加过滤逻辑避免报错:
merged_dict = {item['Key']: item['Value'] for item in original_list if 'Key' in item and 'Value' in item}
内容的提问来源于stack exchange,提问作者user11730572
相关产品推荐
相关产品推荐

