Fast way to copy dictionary in Python(在 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().
这篇关于在 Python 中复制字典的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中复制字典的快速方法
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
