【问题标题】:How to create an element using values of already existed elements in a dict, inside a list?如何使用列表中字典中已存在元素的值创建元素?
【发布时间】:2017-06-21 04:01:05
【问题描述】:

这是我的例子:

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}]

我有带有值的“价格”和“数量”字段。

现在我想创建一个名为“总计”的字段 = 价格 * 数量

如何根据已经存在的 2 个字段的值(值 = 价格 * 数量)创建一个新字段('total': value)?

结果我想看看:

>>> [{'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}]

所以每个字典(字典,是吗?)都扩展了一个新字段“总计”及其值。

如何实现这个想法?

非常感谢任何帮助;)

谢谢!

【问题讨论】:

    标签: list python-3.x dictionary


    【解决方案1】:

    只需遍历您的数据并为您的字典添加一个新键:

    for stock_item in stock_info:
        stock_item["total"] = stock_item["price"] * stock_item["quantity"]
    

    编辑 - 使用您的数据进行测试:

    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}]
    

    【讨论】:

    • 你能说得更准确点吗?这样,只存储最后一个stock_item。 {'total': 19049.102, 'quantity': 20, 'name': 'Alphabet Inc.', 'symbol': 'GOOG', 'price': 952.4551}stock_item 的输出
    • @wingedRuslan - 你检查错了(我猜你正在打印stock_item 而不是stock_info 列表)。 stock_item 只是一个临时参考,真正的变化发生在你的 stock_info 列表的嵌套 dict 项目中。检查上面的例子。
    最近更新 更多