[Python-de] Dictionary und die Methode copy
Jochen Wersdörfer
jochen-python at wersdoerfer.de
Mon Feb 21 01:29:00 CET 2005
On Monday 21 February 2005 00:57, Albert Hermeling wrote:
>
> ich habe ein Dictionary mit Dictionarys als Elemente die wiederrum Listen als
> Elemente enthalten. Das ganze sieht etwa so aus:
>
> Dictionary container:
> {'eins': {'martin': [1, 2, 3]}, 'zwei': {'heinz': [4, 5, 6]}}
>
> wenn ich jetzt container.copy() aufrufe wird von Dictionary container eine
> flache Kopie erzeugt. Die Dictionarys und Listen im Dictionary bleiben davon
> unberührt, sie zeigen nach wie vor auf das Original.
>
> Hat das neue Dictionary zum Beispiel den Namen container1 dann würden sich die
> Daten von "martin" ändern wenn man "martin" im container (Original) ändert.
>
> Gibt es ein Trick den man Anwenden kann, der da zuführt das alle anderen
> Dictionarys und Listen gleich mit kopiert werden? Oder muß ich alle
> Dictionarys und Listen einzeln ansprechen.
Ok, mal sehen:
Python 2.3.5 (#2, Feb 9 2005, 00:38:15)
[GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2
>>> a = {'eins': {'martin': [1, 2, 3]}, 'zwei': {'heinz': [4, 5, 6]}}
>>> b = a.copy()
>>> b['eins']['martin'][0] = 2
>>> a
{'eins': {'martin': [2, 2, 3]}, 'zwei': {'heinz': [4, 5, 6]}}
Tjo, flache Kopie.
>>> from copy import copy
>>> b = copy(a)
>>> b['eins']['martin'][0] = 3
>>> a
{'eins': {'martin': [3, 2, 3]}, 'zwei': {'heinz': [4, 5, 6]}}
Hmm, immer noch flach.
>>> from copy import deepcopy
>>> b = deepcopy(a)
>>> b['eins']['martin'][0] = 4
>>> a
{'eins': {'martin': [3, 2, 3]}, 'zwei': {'heinz': [4, 5, 6]}}
Ha, jetzt gehts :).
Was denn Unterschied angeht, hier mal ein Zitat aus dem docstring:
: x = copy.copy(y) # make a shallow copy of y
: x = copy.deepcopy(y) # make a deep copy of y
:
: The difference between shallow and deep copying is only relevant for
: compound objects (objects that contain other objects, like lists or
: class instances).
:
: - A shallow copy constructs a new compound object and then (to the
: extent possible) inserts *the same objects* into in that the
: original contains.
:
: - A deep copy constructs a new compound object and then, recursively,
: inserts *copies* into it of the objects found in the original.
Gruss,
Jochen