我想复制一个普通的字典
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'}]
但是尊重公共字典的(字段的顺序)必须位于每个输出字典的开头。
考虑到时间和cpu消耗,深度复制是最有效的方法吗?
使用说明:
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+中保持插入顺序,因此这将保证公共字典中的键是第一个。
您可以使用update in-place
如下所示:
你可以在这里阅读:
对于那些参加晚会迟到,我把一些时间放在一起(Py 3.7),表明.update()基础方法看起来有点快(~ 5%)当输入保存和明显(~ 30%)更快的当更新就地。
>>> for ldd in list_data_dictionary:
... ldd.update(*ist_common_dictionary)
>>> list_data_dictionary
[{'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', 'Gender': 'M', 'Age': '25'}]