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}]
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)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.