python - 如何将列表附加到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]}
解决方案
那是因为您将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)
输出是一样的。
推荐阅读
- r - 如何在 R 中创建一个新的数据框,它结合了每个 ID 可用的第一个日期和最后一个日期?
- javascript - 从 sql 表中获取数据并使用 react native 和 js 在屏幕上显示
- c# - Oracle Provider for .NET 不会使用实体框架在实体/表中找到新添加的字段/列(抛出 ORA-00904)
- raspberry-pi - ARM 处理器如何使用超过 4GB 的内存?
- xamarin - Xamarin forms ios - b2c 身份验证在模拟器中有效,但在设备中无效
- fiware - fiwarequantumleap 插入 cratedb 不起作用(缺少架构)
- javascript - 在 react 中跟踪 children prop 的值或事件变化
- javascript - 根据图像文件的实际高度和宽度(React)为图像动态跨越网格行和列
- clickhouse - 我应该使用哪些数据类型将 Jaeger 日志从 Kafka 读取到 Clickhouse?
- javascript - 如何通过与地图元素比较来创建新字符串?