0

I have a list of dictionaries in the form:

mylist = [{1: 0.0, 2: 1.0, 3: 2.0},
          {1: 0.0, 2: 2.3, 3: 1.5},
          {1: 0.6, 2: 1.0, 3: 1.0}]

And a list of the form:

arr = [[1, 0, 0, 1],
       [1, 0, 2, 1],
       [1.0, 1.1, 3.5, 2.0]]

Length of arr is the same as that of mylist. How can I add each element of arr into their corresponding index elements in mylist so that after insertion, mylist is of the form:

mylist = [{1: 0.0, 2 : 1.0, 3: 2.0, 4: 1, 5: 0, 6: 0, 7: 1},
          {1:0.0, 2: 2.3, 3:1.5, 4: 1, 5: 0, 6: 2, 7: 1},
          {1: 0.6, 2: 1.0, 3: 1.0, 4: 1.0, 5: 1.1, 6: 3.5, 7: 2.0}]
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
Saurav--
  • 1,530
  • 2
  • 15
  • 33

1 Answers1

2

enumerate each sublist of arr, starting from 4, and update each dictionary.

You associate the relevant dictionary with the relevant list by zipping them together with zip:

for d, extra in zip(mylist, arr):
    d.update(enumerate(extra, start=4))

enumerate normally counts from 0:

>>> list(enumerate([1, 0, 0, 1]))
[(0, 1), (1, 0), (2, 0), (3, 1)]

You want it to count from 4:

>>> list(enumerate([1, 0, 0, 1], start=4))
[(4, 1), (5, 0), (6, 0), (7, 1)]
Peter Wood
  • 23,859
  • 5
  • 60
  • 99