How to add each item from a list to dictionaries from another list?

Question:

I have the following lists:

A list of dictionaries,

>>> print(*item_cart, sep='n')
{'Item #': 1, 'Price ': 3.99, 'Quantity': 10, 'Name': 'Porcupine'}
{'Item #': 2, 'Price ': 2.99, 'Quantity': 3, 'Name': 'Muffin2'}

and a list of values,

>>> print(specific_item_total)
[39.99, 8.97]

I want to combine the two lists, to create a new list receipt:

>>> print(*receipt, sep='n')
{'Item #': 1, 'Price ': 3.99, 'Quantity': 10, 'Name': 'Porcupine', "Total": 39.99}
{'Item #': 2, 'Price ': 2.99, 'Quantity': 3, 'Name': 'Muffin2', "Total": 8.97}

Obviously, I would need to append specific_item_total into item_cart, and make a for loop to go through each item, and add a new key and value for each already existing dictionary. How would this be done?

Asked By: py_coder1019

||

Answers:

You can use zip:

item_cart = [{'Item #': 1, 'Price ': 3.99, 'Quantity': 10, 'Name': 'Porcupine'}, {'Item #': 2, 'Price ': 2.99, 'Quantity': 3, 'Name': 'Muffin2'}]
specific_item_total = [39.99, 8.97]

output = [{**dct, 'Total': total} for dct, total in zip(item_cart, specific_item_total)]

print(output)
# [{'Item #': 1, 'Price ': 3.99, 'Quantity': 10, 'Name': 'Porcupine', 'Total': 39.99},
#  {'Item #': 2, 'Price ': 2.99, 'Quantity': 3, 'Name': 'Muffin2', 'Total': 8.97}]
Answered By: j1-lee

You can use the new python dictionary merge syntax, together with the zip function:

list(c | {"Total": t} for c, t in zip(item_cart, specific_item_total))
Answered By: Rodrigo Rodrigues
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.