我有一個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})])
所有鍵都具有對相同字典實例的引用,因爲它的值。 –