2017-06-20 84 views
0

我需要爲列表(stock_info)中的每個字典添加stock_quantity的每個值。在列表的每個字典中添加一個元素({「elem」:「value」}),其中value是一個變量

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內)

[{ '符號': 'AAPL', '名':「蘋果公司','price':145.16,'quantity':20},{'symbol':'AMZN','name':'Amazon.com,Inc.','price':998.61,* 'quantity':20 *},{'symbol':'FB','name':'Facebook,Inc.','price':152.96,'量':30},{ '符號': '歌', '名稱': '字母公司', '價格':957.01,'量':20}]

我想這個變體,但它不工作

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

,因爲它實際上追加'量': 'stock_quontity [I] [數量]',但不是stock_quontity的值[I] [量]

任何幫助感激)

謝謝!

回答

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... 
+0

是的,這就是我一直在尋找。您能否簡單解釋一下您的解決方案正在發生什麼? – wingedRuslan

+0

@wingedRuslan:移植添加 – dawg

+0

謝謝!順便說一下,如何創建一個名爲'total'的字段:value,其中value = price * quantity?類似{'symbol':'AAPL','name':'Apple Inc.','price':145.16,'quantity':20,'total':2903.2}這裏是一個[question](https:// stackoverflow.com/questions/44661649/how-to-create-an-element-using-values-of-already-existed-elements-in-a-dict-ins) – wingedRuslan

相關問題