快速的方式来复制Python中的字典 [英] Fast way to copy dictionary in Python

查看:188
本文介绍了快速的方式来复制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.)

键是字符串,值是整数/ 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?

推荐答案

查看 dict 操作的文件/ tip / objects / dictobject.c> C源代码,你可以看到他们做一个非常幼稚。它基本上归结为对 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)

重复相同的对象,如果他们有对象在他们。之后,它做一个大量的一次性resize / alloc到目标dict,然后逐个复制元素。我看不到你比内置的 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中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆