You can write a list comprehension using zip()
to achieve this. Below are few alternatives to achieve this in different Python versions.
In Python 3.9.0+, using |
:
>>> list1 = [{'key1': 'value1'}, {'key2': 'value2'}]
>>> list2 = [100, 200]
>>> [l1 | {'val': v} for l1, v in zip(list1, list2)]
[{'key1': 'value1', 'val': 100}, {'key2': 'value2', 'val': 200}]
In Python 3.5+ using **
>>> [{**l1, 'val': v} for l1, v in zip(list1, list2)]
[{'key1': 'value1', 'val': 100}, {'key2': 'value2', 'val': 200}]
Issue with your code is that your are doing nested iteration of list list2
for both the values of list1
, because of which 'val'
is firstly getting set as 100
and then 200
, and your dictionaries are preserving the last value of list2
i.e. 200. zip()
will let you iterate both the iterables together by fetching element corresponding to same index from both the lists.
Hence, you code using explicit for
loop could be written using zip()
as:
list1 = [{'key1': 'value1'}, {'key2': 'value2'}]
list2 = [100, 200]
for i, j in zip(list1, list2):
i['val'] = j