adplus-dvertising

How to Append a List to a List of Dictionaries?

Asked 2 days ago
Viewed 8 times

I have the following lists:

A list of dictionaries (used for item in list to print item to make look nicer)

print(item_cart)
{'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 look like this: (would use for item in list to print item to make look nicer)

print(receipt) #want the combination of the two to be called receipt
{'Item #': 1, 'Price ': 3.99, 'Quantity': 10, 'Name': 'Porcupine', "Total": 39.99}
{'Item #': 2, 'Price ': 2.99, 'Quantity': 3, 'Name': 'Muffin2', "Total": 8.97}

How would I do this? 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 2 days ago

Correct Answer

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 2 days ago