python - 在字典列表中复制字典对(键,值)并尊重顺序的有效方法

标签 python python-3.x list dictionary memory-management

我想复制一本常用词典

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/

相关文章:

python - 使用Python正则表达式检查文件中的字符串

python - Django-RQ:如何调用函数?

python - 如何在不知道 Python 中将生成多少列的情况下拆分列?

python 的 sum() 和非整数值

C# : Store Generic List<> Objects to File Stream

python - header If-Modified-Since 不给出 304 代码

python - 如何将元音的大写保持在同一位置?

python - 为什么 Python 2 认为这些字节是麦克风表情符号而 Python 3 却不这样认为?

python - 压缩迭代器和计数迭代器的乘积

java - 不知从何而来的空字符串。