-1
lst={1:["O","O","O","O","O"],2:[1,2,3,4,5],3:["a", "b", "c", "d"]}  
for strings in lst[1]:
  lst[1] = lst[1].replace("O","X")
print(lst[1])

This code throws an error:'list' object has no attribute 'replace'. Please tell me how do I replace items in a list?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Aarav Jain
  • 21
  • 1
  • 3
  • 1
    See [this](https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list) – namgold Sep 22 '20 at 07:48

2 Answers2

0

That data structure you're using is not a list it's a dictionary where values are lists.

To get what you want you'd have to this:

d = {1:["O","O","O","O","O"],2:[1,2,3,4,5],3:["a", "b", "c", "d"]}
d[1] = [i.replace("O", "X") for i in d[1]]
print(d)
{1: ['X', 'X', 'X', 'X', 'X'], 2: [1, 2, 3, 4, 5], 3: ['a', 'b', 'c', 'd']}

Or you could iterate over the dictionary items and check if the list contains all strings and the character you want to replace:

old = "O"
new = "X"
d = {1:["O","O","O","O","O"],2:[1,2,3,4,5],3:["a", "b", "c", "d"]}
for key, value in d.items():
    if all(isinstance(item, str) for item in value) and old in value:
       d[key] = [item.replace(old, new) for item in d[key]]
print(d)

Output: {1: ['X', 'X', 'X', 'X', 'X'], 2: [1, 2, 3, 4, 5], 3: ['a', 'b', 'c', 'd']}

baduker
  • 19,152
  • 9
  • 33
  • 56
-1

You can use list comprehension:

lst[1] = [x for x in lst[1] if x is not 'O' else 'X']

or if you know you process a list of string you could do:

csv = "".join(lst[1])
csv.replace('O','X')
lst[1] = csv.split('')
Jean-Marc Volle
  • 3,113
  • 1
  • 16
  • 20