如何在Python字典指定键位置后插入新键值对,避免新增内容到末尾
解决方法
前提说明
Python 3.7及以上版本原生字典默认保留插入顺序,以下方案基于该版本环境实现。如果使用3.6及更低版本,请参考末尾的兼容方案。
核心思路
- 先定位
Teg键在字典键序列中的索引 - 将原字典拆分为
Teg及之前部分、Teg之后部分两个片段 - 合并「前半部分 + 新增键值对 + 后半部分」得到新的有序字典,替换原有字典即可
调整后的代码
import json with open("_test_result.json", encoding="utf-8") as file: result_list = json.load(file) for idx, item in enumerate(result_list[:2]): # 可选:判断如果没有Teg键直接跳过,避免报错 if "Teg" not in item: continue # 获取所有键的列表,定位Teg的位置 keys = list(item.keys()) teg_index = keys.index("Teg") # 拆分原字典 pre_part = {k: item[k] for k in keys[:teg_index+1]} suffix_part = {k: item[k] for k in keys[teg_index+1:]} # 合并得到指定顺序的新字典,替换原有元素 new_item = {**pre_part, "filter": "", "teg2": "", **suffix_part} result_list[idx] = new_item print(new_item) # 若需要保存修改后的数据回原文件,可取消注释下面的代码 # with open("_test_result.json", "w", encoding="utf-8") as file: # json.dump(result_list, file, indent=4, ensure_ascii=False)
低版本Python兼容方案
Python 3.6及更低版本原生字典无序,需要使用collections.OrderedDict实现有序控制:
from collections import OrderedDict import json with open("_test_result.json", encoding="utf-8") as file: # 加载时指定用OrderedDict存储字典结构 result_list = json.load(file, object_pairs_hook=OrderedDict) for idx, item in enumerate(result_list[:2]): if "Teg" not in item: continue keys = list(item.keys()) teg_index = keys.index("Teg") # 按顺序构建新的OrderedDict new_item = OrderedDict() # 先写入Teg及之前的键 for k in keys[:teg_index+1]: new_item[k] = item[k] # 写入新增的两个键 new_item["filter"] = "" new_item["teg2"] = "" # 写入Teg之后的原有键 for k in keys[teg_index+1:]: new_item[k] = item[k] result_list[idx] = new_item print(new_item)
内容的提问来源于stack exchange,提问作者msl
相关产品推荐
相关产品推荐

