Home > OS >  Replacing items in a list with values from a dictionary
Replacing items in a list with values from a dictionary

Time:06-15

I have a dictionary. I want to replace an item of a list with corresponding dictionary value if a key in the dictionary is in the item. For example, if key 'C' is in any item like 'CCC', it will replace the 'CCC' with corresponding dictionary value. Here is my code.

l=['0', 'CCC', '0', 'C', 'D', '0']

dic={"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8}

for i in l:
  
 for k, v in dic.items():
    
  if k in i: i=str(v)

print(l)

What I want to get is: l = ['0', '3', '0', '3', '4', '0']

but the list does not change at all. What am I doing wrong here?

CodePudding user response:

The dictionary isn't changing because when you are iterating the list with for i in l: a new object i is created taking values from the list. Then you are changing the value of i with the appropriate value from the dictionary. However, you are only changing the value of object i. If you want to change the values from the list you should modify the list directly. You can change if k in i: i=str(v) to if k in i: l.insert(l.index(i), v). This will find the location (index) of the key in the list first and then insert the associated value in that index.

Full code:

l=['0', 'CCC', '0', 'C', 'D', '0']

dic={"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8}

for i in l:
  
 for k, v in dic.items():
    
  if k in i: l.insert(l.index(k), v)

print(l)

CodePudding user response:

Based on your comments you can use this example to replace the values in list l:

l = ["0", "CCC", "0", "C", "D", "0"]
dic = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8}

out = [str(dic.get(list(set(v))[0], v)) for v in l]
print(out)

Prints:

['0', '3', '0', '3', '4', '0']
  • Related