gpt4 book ai didi

python - OrderedDict 仅打算更新一个键值对时更新所有键值对

转载 作者:行者123 更新时间:2023-12-01 04:01:50 28 4
gpt4 key购买 nike

我有一个 python OrderedDict,当我只更新一个键值时,所有其他键值对也会更新。我已经包含了下面的源代码和跟踪。

我期望有一个 key 对 (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})])

最佳答案

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 {}

关于python - OrderedDict 仅打算更新一个键值对时更新所有键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36360935/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com