How To Create An Element Using Values Of Already Existed Elements In A Dict, Inside A List?
Here is my example: print (stock_info) >>> [{'symbol': 'AAPL', 'name': 'Apple Inc.', 'price': 145.16, 'quantity': 20}, {'symbol': 'AMZN', 'name': 'Amazon.com, Inc.', 'pric
Solution 1:
Just loop through your data and add a new key to your dictionaries:
forstock_itemin 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)
yields:
[{'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}]
Post a Comment for "How To Create An Element Using Values Of Already Existed Elements In A Dict, Inside A List?"