I have a list of dictionaries and I want to add to each dictionary a new key value pair that I get from another separate list.
This is the list of dictionaries:
arts = [{'Name':'Core', 'Id':20, 'Type':'MP', 'Power':10},
{'Name':'PVC', 'Id':19, 'Type':'MP', 'Power':2}]
I want to achieve the following result:
arts = [{'Name':'Core', 'Id':20, 'Type':'MP', 'Power':10, 'weight':120},
{'Name':'PVC', 'Id':19, 'Type':'MP', 'Power':2, 'weight':1500}]
Getting the weight:value pair from a list like this:
weight = ['120', '1500']
I am trying the following code but it throws me an error:
for elem in arts:
for k in elem.items():
elem['weight'] = [elem]
The mistake is:
RuntimeError: dictionary changed size during iteration
I am using Python 3.6. Thank you very much in advance.
This solution uses the intrinsic function
zip
, which joins two or more iterables together and returns tuples, where each component comes from a different iterable.Since we are no longer iterating over the original dictionary, we can modify it without problems.
produces: