繁体   English   中英

如何将列表中的每个项目添加到另一个列表中的字典?

[英]How to add each item from a list to dictionaries from another list?

我有以下列表:

字典列表,

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

和一个值列表,

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

我想结合这两个列表,创建一个新的列表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}

显然,我需要将 append specific_item_total放入item_cart ,并通过每个项目对 go 进行for循环,并为每个已经存在的字典添加一个新的键和值。 这将如何完成?

您可以使用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}]

您可以使用新的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM