首页 > 解决方案 > 如何将列表附加到python中的现有字典

问题描述

我试图找到与字典中提供的开始日期相距 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]}
    

标签: pythonpython-3.xdictionary

解决方案


那是因为您将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)

输出是一样的。


推荐阅读