0

I am trying to alter values without reassigning any value in the dictionary. But it seems that it works for pop function and not with string functions.

I tried with other list functions and works the same as pop. Looks that list and string work differently when used as values.

my_dict={"Rank":[1,2,3],"Name":"John"}
my_dict.get("Rank").pop()
print(my_dict)
my_dict.get("Name").capitalize()
print(my_dict)
  • `list` objects are mutable. Some methods on lists are mutator methods, that is, they work "in-place". `.pop` is one such method. `str` objects are immutable. That simply means *they lack mutator methods*, so you know that non of their methods will work "in-place". So `.capitalize()` simply returns a new string, which is immediately discarded (since you don't assign it to anything) – juanpa.arrivillaga Aug 15 '19 at 21:03

3 Answers3

1

my_dict.get("Rank") is a mutable list, and you're only using a reference to it. Any changes you make to it, including pop(), will be reflected everywhere.

my_dict.get("Name") is an immutable string. You can't change it, and so capitalize() will return a new string, not modify the existing one.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
  • But dictionaries in Python are Mutable. my_dict.get("Name") value is not stored separately but in dictionary object itself. – Prashant Kumar Gupta Aug 15 '19 at 21:00
  • 1
    @PrashantKumarGupta yes, but you never mutated the dictionary anywhere. You *do* mutate the `list` object, and you *dont* mutate the `str` object, because `str` objects are immutable. – juanpa.arrivillaga Aug 15 '19 at 21:02
  • Why does this also not work `my_dict={"Rank":[1,2,3],"Name":"John","Salary":100.0} my_dict.get("Rank")[1].__add__(1) print(my_dict)` – Prashant Kumar Gupta Aug 15 '19 at 21:37
  • 1
    @PrashantKumarGupta for the very same reason: `int` objects are immutable. This none of their methods work in-place. As an aside, you should pretty much never use a double-underscore method directly like that – juanpa.arrivillaga Aug 15 '19 at 22:08
  • See also e.g. [Python difference between mutating and re-assigning a list](/q/56308475/). – Karl Knechtel Aug 06 '22 at 01:48
0

It's because:

  • list.pop - operates (in-place) on the list itself (removing the (last) element) and thus modifies it
  • [Python 3.Docs]: Built-in Types - str.capitalize() - doesn't operate on the string, but returns a (modified) copy, leaving the original one unchanged

To correct your problem, use:

my_dict["Name"] = my_dict["Name"].capitalize()
CristiFati
  • 38,250
  • 9
  • 50
  • 87
0

caplitalize() returns a str object. If you want to update the value you need to push this back to the dict.

my_dict["Name"] = my_dict.get("Name").capitalize()
Shishir
  • 182
  • 3