Home > Mobile >  How to add each item from a list to dictionaries from another list?
How to add each item from a list to dictionaries from another list?

Time:09-23

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?

CodePudding user response:

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}]

CodePudding user response:

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))
  • Related