I find to find some words in dictionary and replace the with another words . wrote the following code, but there is no change in the output. I don't know how can I change the output?
for elem in output:
for el in elem ['tags']:
if el== 'datamining':
el='data mining'
elif el== 'data science':
el='data mining'
print(output)
new words
d = {
'datamining': 'data mining',
'data science': 'data mining',
}
dictionary
[{'title': 'title1',
'tags': ['datamining', 'data science'
'test\u20',
'data mining',
'test1']},
{'title': 'title2',
'tags': ['title2',
'datamining\u20]
}
]
expected dictionary
[{'title': 'title1',
'tags': ['data mining', 'data mining'
'test\u20',
'data mining',
'test1']},
{'title': 'title2',
'tags': ['title2',
'data mining\u20]
}
]
CodePudding user response:
This should do the trick
for i, elem in enumerate(output):
for j, el in enumerate(elem ['tags']):
if 'datamining' in el:
output[i]['tags'][j]='data mining'
elif 'data science' in el:
output[i]['tags'][j]='data mining'
To eliminate the \u20:
for i, elem in enumerate(output):
for j, el in enumerate(elem ['tags']):
output[i]['tags'][j] = output[i]['tags'][j].replace("\\u20", "")
output[i]['tags'][j] = output[i]['tags'][j].replace('datamining', 'data mining')
output[i]['tags'][j] = output[i]['tags'][j].replace('data science', 'data mining')
CodePudding user response:
for elem in output:
for idx, el in enumerate(elem['tags'][:]):
if el == 'datamining':
elem['tags'][idx] = 'data mining'
elif el == 'data science':
elem['tags'][idx] = 'data mining'
since you cant change an object that you are iterating we make a shallow copy with the slice syntax [:]