0

I have following list, where I try to change all first characters of the keys to upper case with this code:

listOfNames = {
    'tim':1,
    'frank':1
}

for name in listOfNames.keys():
    name = name.capitalize()
    print(name)

I noticed, that when I leave out the assignment of the variable name like follows:

for name in listOfNames.keys():
    name.capitalize()
    print(name)

It prints out all the keys without changing them. Now if I understood it correctly, name is only a copy of the key. But I run the method capitalize on that copy. Why doesnt it return the key with upper case when I leave out name = name.capitalize()?

malkmand
  • 3
  • 1
  • 3
    `name.capitalize()` returns a new string, it doesn't change the original one. – Thierry Lathuille Sep 24 '19 at 17:13
  • 1
    If you are only just learning the basics, you should probably ignore Python 2, and spend your time on the currently recommended and supported version of the language, which is Python 3. – tripleee Sep 24 '19 at 17:16
  • In order to do replace the keys you should delete the old key and create a new key. – Aviv Bar-el Sep 24 '19 at 17:20

1 Answers1

0

Because strings are immutable, they can't be changed in-place, so calling:

name.capitalize()  #  or any other method

returns a new string rather than modifying name in-place, and to achieve what you want, you can use a dict comprehension:

listOfNames = {
    k.capitalize() : v for k, v in listOfNames.items()
}
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55