在列表的每个字典中添加元素({“elem”:“value”}),其中value是变量

时间:2017-06-20 16:05:15

标签: list python-3.x dictionary append

我需要在列表(stock_info)中的每个字典中添加stock_quantity的每个值。

print (stock_info)
>>> [{'symbol': 'AAPL', 'name': 'Apple Inc.', 'price': 145.16}, {'symbol': 'AMZN', 'name': 'Amazon.com, Inc.', 'price': 998.61}, {'symbol': 'FB', 'name': 'Facebook, Inc.', 'price': 152.96}, {'symbol': 'GOOG', 'name': 'Alphabet Inc.', 'price': 957.01}]

print (stock_quantity)
>>> [{'quantity': 20}, {'quantity': 20}, {'quantity': 30}, {'quantity': 20}]

结果我想看到:(因此数量在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。','价格':152.96, '数量':30 },{'symbol':'GOOG', 'name':'Alphabet Inc.','price':957.01, 'quantity':20 }]

    
  

我尝试了这个变种,但它不起作用

i = 0
for item in stock_info:
    item.update ( { "quantity": "stock_quontity[i][quantity] "})
    i += 1

因为它实际上附加 '数量':'stock_quontity [i] [数量]' ,而不是stock_quontity [i] [数量]的值

非常感谢任何帮助;)

谢谢!

1 个答案:

答案 0 :(得分:0)

你可以这样做:

for (i,d1), d2 in zip(enumerate(stock_info), stock_qty):
    d1.update(d2)
    stock_info[i]=d1

>>> 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 (i,d1), d2 in zip(enumerate(stock_info), stock_qty)
 ^                                       for loop
      ^                                  unpack the tuple from enumerate     
          ^                              unpack the tuple from zip 
                   ^                     zip the two lists into pairs of elements
                        ^                enumerate the list we are changing

   d1.update(d2)
       ^                                 add d2 to d1

   stock_info[i]=d1
       ^                                 change the d1 in stock_info
   WARNING: careful changing lists you are interating over. 
   Don't change their length...