-1

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]

mona
  • 1
  • 3
  • Welcome to Stack Overflow. Where exactly are you stuck with this problem? Please read [ask] and https://meta.stackoverflow.com/questions/334822, and then try to think about the problem logically. What steps need to be taken in order to get the answer? What parts don't you know how to do? For those parts, [can you find](https://meta.stackoverflow.com/questions/261592) an answer with a search engine? – Karl Knechtel Jun 15 '22 at 03:46
  • Does this answer your question? [How to change the values of only part (slice) of a list of strings](https://stackoverflow.com/questions/51487677/how-to-change-the-values-of-only-part-slice-of-a-list-of-strings) – Alexander Jun 15 '22 at 07:41

3 Answers3

1

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.

Daniel
  • 11,332
  • 9
  • 44
  • 72
-1
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]

Nicolas Perez
  • 354
  • 1
  • 9
-1
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]
mNauhH
  • 62
  • 3