2016-04-01 59 views
1

我有一個Python OrderedDict,當我只更新一個鍵值時,所有其他鍵值對都會得到更新。我已經包含源代碼和從下面跟蹤。OrderedDict當只更新一個鍵值對時更新所有鍵值對

我期待有一對(2014,{'start':2014,'end':2015}),但這裏並不是這種情況。

import datetime 
import collections 
import math 
from decimal import Decimal 
from dateutil.relativedelta import relativedelta 



def get_ordered_dict(start, end, intial_value): 
    d = collections.OrderedDict() 
    for i in range(start, end+1): 
     d[i] = intial_value 
    return d 


start_year = 2014 
end_year = start_year + 39 + 1 
od = get_ordered_dict(start_year, end_year, {}) 

for year in od.keys(): 
    print year 
    d = od[year] 
    d['start'] = year 
    d['end'] = year + 1 
    print od 

返回:

OrderedDict([(2014, {'end': 2053, 'start': 2052}), 
      (2015, {'end': 2053, 'start': 2052}), 
      (2016, {'end': 2053, 'start': 2052}), 
      (2017, {'end': 2053, 'start': 2052}), 
      (2018, {'end': 2053, 'start': 2052}), 
      (2019, {'end': 2053, 'start': 2052}), 
      (2020, {'end': 2053, 'start': 2052}), 
      (2021, {'end': 2053, 'start': 2052}), 
      (2022, {'end': 2053, 'start': 2052}), 
      (2023, {'end': 2053, 'start': 2052}), 
      (2024, {'end': 2053, 'start': 2052}), 
      (2025, {'end': 2053, 'start': 2052}), 
      (2026, {'end': 2053, 'start': 2052}), 
      (2027, {'end': 2053, 'start': 2052}), 
      (2028, {'end': 2053, 'start': 2052}), 
      (2029, {'end': 2053, 'start': 2052}), 
      (2030, {'end': 2053, 'start': 2052}), 
      (2031, {'end': 2053, 'start': 2052}), 
      (2032, {'end': 2053, 'start': 2052}), 
      (2033, {'end': 2053, 'start': 2052}), 
      (2034, {'end': 2053, 'start': 2052}), 
      (2035, {'end': 2053, 'start': 2052}), 
      (2036, {'end': 2053, 'start': 2052}), 
      (2037, {'end': 2053, 'start': 2052}), 
      (2038, {'end': 2053, 'start': 2052}), 
      (2039, {'end': 2053, 'start': 2052}), 
      (2040, {'end': 2053, 'start': 2052}), 
      (2041, {'end': 2053, 'start': 2052}), 
      (2042, {'end': 2053, 'start': 2052})]) 
+0

所有鍵都具有對相同字典實例的引用,因爲它的值。 –

回答

2

def get_ordered_dict(start, end, intial_value): 
    d = collections.OrderedDict() 
    for i in range(start, end+1): 
     d[i] = intial_value 
    return d 

分配給每一個d[i]到同一initial_value參考,相同的單詞在這種情況下

od = get_ordered_dict(start_year, end_year, {}) 

因此,在你的循環中,你一遍又一遍地修改同一個字典。分配一個唯一的字典參考

的一種方法是使initial_value的(淺)副本:

d[i] = intial_value.copy() # [sic] 

你也可以將initial_value關鍵字參數默認爲None

def get_ordered_dict(start, end, intial_value=None): 
    ... 
     # assuming intial_value will always be a dict 
     d[i] = intial_value.copy() if intial_value is not None else {} 
+0

優秀的解釋,你能提供一個合適的解決方案嗎?甚至提示解決這個問題? –

0

要解決該問題,請改用d[i] = intial_value.copy()以確保每個條目都是不同的空字典。