如何使用列表中的字典中已存在元素的值创建元素? [英] How to create an element using values of already existed elements in a dict, inside a list?
本文介绍了如何使用列表中的字典中已存在元素的值创建元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的例子:
print (stock_info)
>>> [{'symbol': 'AAPL', 'name': 'Apple Inc.', 'price': 145.16, 'quantity': 20}, {'symbol': 'AMZN', 'name': 'Amazon.com, Inc.', 'price': 998.61, 'quantity': 20}, {'symbol': 'FB', 'name': 'Facebook, Inc.', 'price': 152.96, 'quantity': 30}, {'symbol': 'GOOG', 'name': 'Alphabet Inc.', 'price': 957.01, 'quantity': 20}]
我有带有价格的价格"和数量"字段.
I have 'price' and 'quantity' fields with values.
现在我想创建一个名为总计" =价格*数量的字段
And now I would like to create a field called 'total' = price * quantity
如何基于已经存在的2个字段的值(值=价格*数量)创建一个新字段(总计":值)?
How to create a new field ('total': value) based on values of 2 fields, which already exist ( value = price * quantity)?
因此,我想看看:
>>> [{'symbol': 'AAPL', 'name': 'Apple Inc.', 'price': 145.16, 'quantity': 20, 'total' : 2903.2}, {'symbol': 'AMZN', 'name': 'Amazon.com, Inc.', 'price': 998.61, 'quantity': 20, 'total' : 19972.2}, {'symbol': 'FB', 'name': 'Facebook, Inc.', 'price': 152.96, 'quantity': 30, 'total' : 4588.8}, {'symbol': 'GOOG', 'name': 'Alphabet Inc.', 'price': 957.01, 'quantity': 20, 'total' : 19140.2}]
因此,每个dict(dict,是吗?)都使用新的字段"total"及其值进行了扩展.
So each dict (dict, yes?) was extended with a new field 'total' and its value.
如何实现这个想法?
非常感谢您的帮助;)
谢谢!
推荐答案
只需遍历数据并向字典添加新键:
Just loop through your data and add a new key to your dictionaries:
for stock_item in stock_info:
stock_item["total"] = stock_item["price"] * stock_item["quantity"]
编辑-使用数据进行测试:
EDIT - Testing with your data:
stock_info = [{'symbol': 'AAPL', 'name': 'Apple Inc.', 'price': 145.16, 'quantity': 20},
{'symbol': 'AMZN', 'name': 'Amazon.com, Inc.', 'price': 998.61, 'quantity':20},
{'symbol': 'FB', 'name': 'Facebook, Inc.', 'price': 152.96, 'quantity': 30},
{'symbol': 'GOOG', 'name': 'Alphabet Inc.', 'price': 957.01, 'quantity': 20}]
for stock_item in stock_info:
stock_item["total"] = stock_item["price"] * stock_item["quantity"]
print(stock_info)
产量:
[{'name': 'Apple Inc.', 'price': 145.16, 'symbol': 'AAPL', 'total': 2903.2, 'quantity': 20},
{'name': 'Amazon.com, Inc.', 'price': 998.61, 'symbol': 'AMZN', 'total': 19972.2, 'quantity': 20},
{'name': 'Facebook, Inc.', 'price': 152.96, 'symbol': 'FB', 'total': 4588.8, 'quantity': 30},
{'name': 'Alphabet Inc.', 'price': 957.01, 'symbol': 'GOOG', 'total': 19140.2, 'quantity': 20}]
这篇关于如何使用列表中的字典中已存在元素的值创建元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文