0

Changes also appear on the main object even though saved only on a different object?

A dict:
transportation = {"car":"ford", "coche":"fiat"}
The changes:
x = transportation.setdefault("carro", "BMW")
Output of the object where changes were stored(x):
BMW
Output of the original dict:
{"car":"ford", "coche":"fiat", "carro", "BMW"}
  • 2
    Does this answer your question? [List changes unexpectedly after assignment. How do I clone or copy it to prevent this?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) The link is about `list`s not `dict`s, but the fundamental problem is the same. – 0x5453 Feb 23 '21 at 21:53

1 Answers1

1

Dict is mutable object. Which means you are assigning a reference to the same dict. Instead try

x = transportation.copy().setdefault("carro", "BMW")

See here

Ryan Dempsey
  • 97
  • 1
  • 9
  • I just remembered how it works. Thank you for your contribution. With copy() method we create a copy not linked to the original but an oposed result with a simple atribution. – Brunno Silva Feb 24 '21 at 00:38