我想复制一本常用词典
list_common_dictionary = [{'Gender':'M', 'Age':'25'}]
数据列表字典内\
list_data_dictionary = [{'name':'john','id':'1'},
{'name':'albert','id':'2'},
{'name':'jasper','id':'3'},
{'name':'guillaume','id':'4'}]
并获得如下输出:
output_dictionary = [{'Gender':'M', 'Age':'25','name':'john','id':'1'},
{'Gender':'M', 'Age':'25','name':'albert','id':'2'},
{'Gender':'M', 'Age':'25','name':'jasper','id':'3'},
{'Gender':'M', 'Age':'25','name':'guillaume','id':'4'}]
但要遵守 (公共(public)字典的字段必须位于每个输出字典的开头。
关于时间cpu消耗,deepcopy是最有效的方法吗?
最佳答案
用途:
result = [{**list_common_dictionary[0], **d} for d in list_data_dictionary]
print(result)
输出
[{'Gender': 'M', 'Age': '25', 'name': 'john', 'id': '1'}, {'Gender': 'M', 'Age': '25', 'name': 'albert', 'id': '2'}, {'Gender': 'M', 'Age': '25', 'name': 'jasper', 'id': '3'}, {'Gender': 'M', 'Age': '25', 'name': 'guillaume', 'id': '4'}]
字典在 Python 3.6+ 中保持插入顺序,因此这将保证公共(public)字典中的键是第一个。
关于python - 在字典列表中复制字典对(键,值)并尊重顺序的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69556036/