Python修改字典列表元素时单条更新却同步修改所有索引如何解决
问题根因
你使用np.repeat()生成updated列表时,仅复制了原字典对象的内存引用,列表中所有元素指向同一个字典实例,修改任意一个元素的属性都会同步作用到所有引用指向的同一块内存空间,因此出现所有索引值同步更新的问题。
修复方案
替换np.repeat逻辑,对每个需要生成的option项做深拷贝,确保每个列表元素都是独立的字典实例:
- 引入
copy模块的deepcopy方法处理嵌套字典的深拷贝 - 循环生成对应数量的独立option对象
完整修复代码
import copy list_foci=["Erbschaftssteuerrecht","Erbrecht"] list_size=len(list_foci) dynamic_list= [ { "title": "What time do you want your appointment?", "options": [ { "label": "Monday 1:00 pm", "value": { "input": { "text": "Monday 1:00 pm" } } } ], "description": "", "response_type": "option" } ] # 替换np.repeat逻辑,深拷贝生成独立的option对象 updated = [copy.deepcopy(dynamic_list[0]['options'][0]) for _ in range(list_size)] response={ "arr": [ { "title": "Wählen Sie das passende Rechtsgebiet:", "options": updated, "description": "", "response_type": "option" } ] } response['arr'][0]['options'][0]['label']= "Contract Law" response['arr'][0]['options'][0]['value']['input']['text'] = "Contract Law" response['arr'][0]['options'][1]['label']= "Sales Law" response['arr'][0]['options'][1]['value']['input']['text'] = "Sales Law" print(response)
运行输出验证
修改后打印的response中两个option的值为独立值,不会同步更新:
{'arr': [{'title': 'Wählen Sie das passende Rechtsgebiet:', 'options': [{'label': 'Contract Law', 'value': {'input': {'text': 'Contract Law'}}}, {'label': 'Sales Law', 'value': {'input': {'text': 'Sales Law'}}}], 'description': '', 'response_type': 'option'}]}
内容的提问来源于stack exchange,提问作者Aymal Khan
相关产品推荐
相关产品推荐

