Home > Mobile >  operation on string items in python dict
operation on string items in python dict

Time:05-19

I found some unexpected behavior while trying to edit strings in a dictionary (python 3.8.9.0), the new value does not make it into the string.

A dictionary of lists appends as expected

a = {'a':[]}
for k, v in a.items():
   v =['o']
   
a
Out[24]: {'a': ['o']}

A dictionary of strings does not update:

a = {'a':'a'}
for k, v in a.items():
   v ='o'
   
a
Out[27]: {'a': 'a'}

CodePudding user response:

Strings are immutable, adding another string even in place leads to a new string, but you can use dict setting for the same thing.

d = {}

d[1] = "a"
print(id(d[1]), d[1])  # 4302987632 a

s = d[1]
print(id(s), s)  # 4302987632 a

s  = "c"
print(id(s), s)  # 4672398256 ac

d[1]  = "d"
print(id(d[1]), d[1])  # 4646283568 ad but this time it is placed in the dict

CodePudding user response:

This is because lists are mutable, and strings are not. To get the more "expected" (by some definition) behavior, modify the original dictionary value. Example:

a = {'a':'a'}
for k, v in a.items():
   v  = 'o'
print(a)
# {'a': 'a'}

for k, v in a.items():
   a[k]  = 'o'
print(a)
# {'a': 'ao'}
  • Related