我试图找到日期27至33天除了在字典中提供的开始日期;但是,我不能将新的日期追加到键值组合对。我一直得到一个错误,不能分配给一个函数调用。如有任何帮助,不胜感激。
dictionary_items = {"one": [20210101], "two": [20210202], "three": [20210303], "four": [20210404]}
dictionary_items = dictionary_items.items()
for key, value in dictionary_items:
temp_var = []
value = value[-1]
temp_var.append(value)
for date in range(20210101, 20210531, 1):
x = (date - value) + 1
if 27 <= x <= 33:
temp_var.append(date)
dictionary_items[key] = temp_var
print(dictionary_items)
期望输出:
{"one": [20210101, Date2, Date3], "two": [20210202, Date2, Date3], "three": [20210303, Date2, Date3],
"four": [20210404, Date2, Date3]}
这是因为您将dictionary_items
标签重新定义为.items()
,并且您正在尝试将项目添加到items
视图。它只是原始字典的一个视图对象,你应该向字典本身添加项:
dictionary = {"one": [20210101], "two": [20210202], "three": [20210303], "four": [20210404]}
for key, value in dictionary.items():
temp_var = []
value = value[-1]
temp_var.append(value)
for date in range(20210101, 20210531, 1):
x = (date - value) + 1
if 27 <= x <= 33:
temp_var.append(date)
dictionary[key] = temp_var
print(dictionary)
输出:
{'one': [20210101, 20210127, 20210128, 20210129, 20210130, 20210131, 20210132, 20210133], 'two': [20210202, 20210228, 20210229, 20210230, 20210231, 20210232, 20210233, 20210234], 'three': [20210303, 20210329, 20210330, 20210331, 20210332, 20210333, 20210334, 20210335], 'four': [20210404, 20210430, 20210431, 20210432, 20210433, 20210434, 20210435, 20210436]}
这些临时变量可以被删除:
dictionary = {"one": [20210101], "two": [20210202], "three": [20210303], "four": [20210404]}
for key, value in dictionary.items():
for date in range(20210101, 20210531):
x = (date - value[0]) + 1
if 27 <= x <= 33:
dictionary[key].append(date)
print(dictionary)
输出相同。