1

Could you please explain, why v2 doesn't contain {"A": 1, "B": 2, "C": 3} and v3 does?

class MyClass:

    def foo(self):

        v1 = self.d.get('A')
        print(v1)
        # 1

        v2 = self.d.update({"C": 3})
        print(v2)
        # None

        v3 = self.d
        v3.update({"C": 3})
        print(v3)
        # {'A': 1, 'B': 2, 'C': 3}

    @property
    def d(self):
        return {"A": 1, "B": 2}

mc = MyClass()
mc.foo()
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Konstantin
  • 2,937
  • 10
  • 41
  • 58
  • 2
    `dict.update` is an *in-place* operation, it doesn't return anything (well, it returns `None`). If you just `print(self.d)` *before* creating `v3` you'll see `self.d["C"]` is already `3`. Canonical duplicate: https://stackoverflow.com/q/1452995/3001761. – jonrsharpe Aug 06 '18 at 17:11
  • @jonrsharpe Thank you for the reply! I completely forgot about it. – Konstantin Aug 06 '18 at 17:15

1 Answers1

1

self.d.update({"C": 3}) is a void function. It returns a None value. In your case, v2 is being re-assigned to None.

Alan Raso
  • 263
  • 2
  • 9