[英]How to add each item from a list to dictionaries from another list?
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
:我想结合这两个列表,创建一个新的列表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.显然,我需要将 append specific_item_total
放入item_cart
,并通过每个项目对 go 进行for
循环,并为每个已经存在的字典添加一个新的键和值。 How would this be done?这将如何完成?
You can use zip
:您可以使用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}]
You can use the new python dictionary merge syntax, together with the zip
function :您可以使用新的 python 字典合并语法以及zip
function :
list(c | {"Total": t} for c, t in zip(item_cart, specific_item_total))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.