Reputation: 1971
Set-up
I have a dictionary where each key contains a list of at least one string element.
Here is a part of the dictionary,
d = {
'Bergen-Enkheim': ['Bergen-Enkheim'],
'Bornheim/Ostend': ['Ostend,\xa0Bornheim'],
'Harheim': ['Harheim'],
'Innenstadt I': ['Altstadt,\xa0Bahnhofsviertel,\xa0Gallus,'
'\xa0Gutleutviertel,\xa0Innenstadt']
}
Most of the elements start with \xa0
which I want to replace with a white space.
I tried the following loop,
for key in d:
for x in d[key]:
x = x.replace('\xa0', ' ')
but d
stays the same. How do I replace the unwanted characters with a white space?
Upvotes: 0
Views: 841
Reputation: 22875
You can iterate over keys and then update values
for key in d:
d[key] = [s.replace('\xa0', '') for s in d[key]]
Upvotes: 1
Reputation: 9010
Strings are immutable, so x.replace(...)
produces a new string rather than changing the existing string in the dictionary list. Then, the statement x = ...
updates x
to be a name for the new string. In short, you have to change the entry in the dictionary list explicitly.
for key in d2:
for i, x in enumerate(d2[key]):
d2[key][i] = x.replace('\xa0', ' ')
Upvotes: 1
Reputation: 22942
You can use a classic iteration over the values:
for values in d.values():
values[:] = [x.replace('\xa0', ' ') for x in values]
Each list is modified in-place.
Upvotes: 1