0

I have list and i want to replace all the elements os the list with another elements.
Code:

list1 = ['1','1','3','4','5','2','3','4']                                           
dict1 = {'dict1' : ['1','2','3','4','5'] ,'name':['su5','pra4','sa3','ma2','sri1']}            
for x in range(len(dict1['dict1'])):    
      list1 = [word.replace(dict1['dict1'][x],dict1['name'][x]) for word in list1]   
print(list1)

Actual Output:

['susri1', 'susri1', 'sa3', 'ma2', 'sri1', 'prama2', 'sa3', 'ma2']  

Expected Output:

['su5','su5','sa3','ma2','sri1','pra4','sa3','ma2']
2
  • What if an element is '12'? Do you want to rename it to su5pra4? Commented Aug 3, 2017 at 13:53
  • No I don't want to rename as su5pra4. Commented Aug 3, 2017 at 14:32

1 Answer 1

4

That's a very strange dictionary if you transform the dictionary so you can use it as a direct mapping then this is a relatively easy thing to do, e.g.:

>>> dict2 = dict(zip(dict1['dict1'], dict1['name']))
>>> [dict2[i] for i in list1]
['su5', 'su5', 'sa3', 'ma2', 'sri1', 'pra4', 'sa3', 'ma2']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.