2016-02-16 41 views
0

我的要求是一旦所有條件滿足,就用另一個字典更新字典。 這是一個類似的代碼片段;如何用其他詞典更新全球詞典?

hello = {} 
he = {"a":1} 
j = 0 
def abc(i): 
    if i % 2 == 0: 
     hello["b"] = i #<----- Error occurs here 
     print hello  #<----- Error occurs here 
    else: 
     hello.clear() #<----- Error occurs here 
     hello = he  #Because of this line error occurs in the above lines 
     print hello 
while j < 15: 
    print "j = ", j 
    abc(j) 
    j += 1 

當我宣佈全球在def abc(i),錯誤消失,但輸出只是的bizzare。

hello = {} 
he = {"a":1} 
j = 0 
def abc(i): 
    global he, hello 
    if i % 2 == 0: 
     hello["b"] = i 
     print hello 
    else: 
     hello.clear() 
     hello = he 
     print hello 
while j < 15: 
    print "j = ", j 
    abc(j) 
    j += 1 

它清除並更新都hellohe自動,那裏因爲沒有operatiosn是在he發生。 如何解決此問題。

+1

這裏有很多事情要做,首先,你在使用全局變量時要小心。在這種情況下,最好將'hello'和'he'作爲參數傳遞給'abc'。其次,當你設置'hello = he'時,你不會將'he'的內容複製到'hello',你正在創建一個綁定。在這裏閱讀以獲得更多信息:https://docs.python.org/2/library/copy.html –

+0

當你將'hello'設置爲'he'時,你基本上將'hello'指向'he'而不是創建新副本 – danidee

+0

我們還應該注意,由於賦值運算符的默認行爲,函數內部的'hello'對於該函數來說是本地的。 'hello = he'行不會影響代碼頂部的'hello'變量。 – TheSchwa

回答

1

你需要hello是全球性的,當你分配he它,但只是說hello = he使得hello參考he。它現在是同一本詞典的另一個名稱。要解決您的問題,請說hello = he.copy()