Home > OS >  How do I use dictionary to replace numbers in a list?
How do I use dictionary to replace numbers in a list?

Time:06-15

Suppose we have a vector of 1’s of size = 10. How can we write a code where the key is index and the value is replacing_number. Eg.

Vector = [1,1,1,1,1,1,1,1,1,1]
Dict = {2:4, 6:9, 9:3}

Output will be [1,4,1,1,1,9,1,1,3,1]

CodePudding user response:

You can try the following:

for key, value in Dict.items():
    Vector[key-1] = value

Note I'm subtracting one because your dictionary seems to count starting at 1, but python starts counting at 0.

CodePudding user response:

Vector = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Dict = {2: 4, 6: 9, 9: 3}

for k, v in Dict.items():
    Vector[k - 1] = v

print(Vector)
# output: [1, 4, 1, 1, 1, 9, 1, 1, 3, 1]

CodePudding user response:

for k in d:
    if k > 0 and k <= len(v):
        v[k - 1] = d[k]

you can try loop for in dictionary like above. Hope it helpful for you Addtionally your output is not correct

Output will be [1,4,1,1,1,9,1,1,4,1]
it should be   [1,4,1,1,1,9,1,1,3,1]

CodePudding user response:

Using list comprehension with enumerate and dict.get:

vct = [1,1,1,1,1,1,1,1,1,1]
dct = {2:4, 6:9, 9:3}

output = [dct.get(i, x) for i, x in enumerate(vct, start=1)]
print(output) # [1, 4, 1, 1, 1, 9, 1, 1, 3, 1]
  • Related