Seite 1 von 1

Kopie eines Dictionaries mit Unterlisten

Verfasst: Mittwoch 4. Juni 2008, 10:14
von martin86_mu
Hi, wenn ich ein Dictionary mit Listen als Values mit copy() kopiere und danach im kopierten eine Liste verändere wird auch das original verändert. An was liegt das? Beispiel:

Code: Alles auswählen

DctLst = { 'x': [1,2,3,4,5], 'y':[100,200,300], 'z':0.01}

DctLstCopy = DctLst.copy()

DctLstCopy['x'].append(6)
DctLstCopy['z'] = 0

print "DctLst =",DctLst
print "DctLstCopy =",DctLstCopy
ergibt:

Code: Alles auswählen

DctLst = {'y': [100, 200, 300], 'x': [1, 2, 3, 4, 5, 6], 'z': 0.01}
DctLstCopy = {'y': [100, 200, 300], 'x': [1, 2, 3, 4, 5, 6], 'z': 0}
Eigentlich wollte ich die Originale DctLst nicht mit der 6 ergänzen. Hat jemand ne Erklärung/Abhilfe. Gruß und danke im voraus

Verfasst: Mittwoch 4. Juni 2008, 10:30
von Hyperion
http://docs.python.org/lib/module-copy.html

Das sollte alles erklären! Du brauchst also deepcopy()!

Verfasst: Mittwoch 4. Juni 2008, 10:30
von BlackJack
Die `dict.copy()`-Methode erzeugt nur eine flache Kopie, dass heisst im neuen Dictionary sind Kopien der Referenzen auf die Objekte im alten Dictionary. Schau mal ins `copy`-Modul, da gibt's eine `deepcopy()`-Funktion.

Verfasst: Mittwoch 4. Juni 2008, 10:35
von martin86_mu
Hi, danke euch. Perfekt. gruß