在 Python 中复制字典的快速方法
问题描述
我有一个 Python 程序,可以经常使用字典.我必须复制字典数千次.我需要密钥和相关内容的副本.副本将被编辑,并且不得链接到原件(例如,副本中的更改不得影响原件.)
I have a Python program that works with dictionaries a lot. I have to make copies of dictionaries thousands of times. I need a copy of both the keys and the associated contents. The copy will be edited and must not be linked to the original (e.g. changes in the copy must not affect the original.)
键是字符串,值是整数 (0/1).
Keys are Strings, Values are Integers (0/1).
我目前使用一个简单的方法:
I currently use a simple way:
newDict = oldDict.copy()
分析我的代码显示复制操作花费了大部分时间.
Profiling my Code shows that the copy operation takes most of the time.
dict.copy()
方法是否有更快的替代方法?什么是最快的?
Are there faster alternatives to the dict.copy()
method? What would be fastest?
解决方案
看C源码 对于 Python dict
操作,您可以看到它们做了一个非常幼稚(但高效)的复制.它本质上归结为对 PyDict_Merge
的调用:
Looking at the C source for the Python dict
operations, you can see that they do a pretty naive (but efficient) copy. It essentially boils down to a call to PyDict_Merge
:
PyDict_Merge(PyObject *a, PyObject *b, int override)
这会快速检查它们是否是同一个对象以及它们是否有对象.之后,它会对目标 dict 进行一次慷慨的 resize/alloc,然后一个一个地复制元素.我没有看到你比内置的 copy()
快得多.
This does the quick checks for things like if they're the same object and if they've got objects in them. After that it does a generous one-time resize/alloc to the target dict and then copies the elements one by one. I don't see you getting much faster than the built-in copy()
.
相关文章