0

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
py_coder1019
  • 95
  • 1
  • 8
  • 1
    That's not a list. There's no `[]` around it. – Barmar Sep 23 '22 at 00:43
  • Don't write `print(item_cart)` if that's not what you actually used to print the two lines. – chepner Sep 23 '22 at 00:52
  • 1
    Does this answer your question? [How do I iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-do-i-iterate-through-two-lists-in-parallel) – mkrieger1 Sep 23 '22 at 00:57

2 Answers2

1

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}]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

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))
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36