我要復制一本普通詞典
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 消耗,deepcopy 是最有效的方法嗎?
uj5u.com熱心網友回復:
用:
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 中保持插入順序,因此這將保證公共字典中的鍵是第一個。
uj5u.com熱心網友回復:
您可以使用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'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/312947.html
上一篇:使用字典更新索引值列
