简体   繁体   English

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

[英]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.

相关问题 将字典列表中的数字添加到另一个字典列表 - Add numbers from a list of dictionaries to another list of dictionaries 从另一个字典列表创建字典列表 - Creating a list of dictionaries from another list of dictionaries 从词典列表中提取项目 - extract item from list of dictionaries 从字典列表中筛选出每个项目的最小值 - From list of dictionaries filter out, for each item, it's lowest value 如果与列表中每个字典中的一个键的值匹配,则将具有不同词典值的新键添加到词典列表中 - Add new key to list of dictionaries with the values from a different dictionaries if matched with value of one key in each dictionary in a list 如何将列表中的值添加到 RDD 的每个项目中? - How do I add values from a list into each item of an RDD? 从另一个词典列表中减去词典列表中的值 - Subtract values from list of dictionaries from another list of dictionaries 如何将字典列表添加到另一个字典列表中? - How do I add a list of dictionaries to another list of dictionaries? 将一个列表中的每个项目添加到另一个列表中的每个项目到第三个列表 - Adding each item from one list to each item from another list to third list 如何将一个列表中的项目追加到另一个列表? - How to append a item from a list to another list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM