You need to zip, iterate over each sublist from u,deepcopy each dict from v and add the new key/value pairing, finally append the new dict to a list:
from copy import deepcopy
u= [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '10']]
v=[{'id': 'a', 'adj': ['blue', 'yellow']}, {'id': 'b', 'adj': ['purple', 'red']}, {'id': 'c', 'adj': ['green', 'orange']}, {'id': 'd', 'adj': ['black', 'purple']}]
out = []
# match up corresponding elements fromm both lists
for dct, sub in zip(v, u):
# iterate over each sublist
for val in sub:
# deepcopy the dict as it contains mutable elements (lists)
dct_copy = deepcopy(dct)
# set the new key/value pairing
dct_copy["value"] = val
# append the dict to our out list
out.append(dct_copy)
from pprint import pprint as pp
pp(out)
Which will give you:
[{'adj': ['blue', 'yellow'], 'id': 'a', 'value': '1'},
{'adj': ['blue', 'yellow'], 'id': 'a', 'value': '2'},
{'adj': ['purple', 'red'], 'id': 'b', 'value': '3'},
{'adj': ['green', 'orange'], 'id': 'c', 'value': '4'},
{'adj': ['green', 'orange'], 'id': 'c', 'value': '5'},
{'adj': ['green', 'orange'], 'id': 'c', 'value': '6'},
{'adj': ['black', 'purple'], 'id': 'd', 'value': '7'},
{'adj': ['black', 'purple'], 'id': 'd', 'value': '8'},
{'adj': ['black', 'purple'], 'id': 'd', 'value': '9'},
{'adj': ['black', 'purple'], 'id': 'd', 'value': '10'}]
dicts have a .copy
attribute or you could call dict(dct)
but because you have mutable object as values, just doing a shallow copy will not work. The example below shows you the actual difference:
In [19]: d = {"foo":[1, 2, 4]}
In [20]: d1_copy = d.copy() # shallow copy, same as dict(d)
In [21]: from copy import deepcopy
In [22]: d2_copy = deepcopy(d) # deep copy
In [23]: d["foo"].append("bar")
In [24]: d
Out[24]: {'foo': [1, 2, 4, 'bar']}
In [25]: d1_copy
Out[25]: {'foo': [1, 2, 4, 'bar']} # copy also changed
In [26]: d2_copy
Out[26]: {'foo': [1, 2, 4]} # deepcopy is still the same
what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignment