【问题标题】:Complete list of dictionaries with date and zero values for the missing months in a range范围内缺失月份的日期和零值的字典的完整列表
【发布时间】:2021-11-22 23:04:27
【问题描述】:

我有一个这样的字典列表:

[{'start_date': '2021-05', 'value': 1500.0},
 {'start_date': '2021-08', 'value': 6000.0},
 {'start_date': '2021-09', 'value': 3000.0},
 {'start_date': '2021-10', 'value': 2750.0},
 {'start_date': '2021-11', 'value': 19500.0}]

我想用'value': 0添加缺少的月份(start_date)。

我想要从上面的字典中得到的输出是:

[{'start_date': '2021-05', 'value': 1500.0},
 {'start_date': '2021-06', 'value': 0},
 {'start_date': '2021-07', 'value': 0},
 {'start_date': '2021-08', 'value': 6000.0},
 {'start_date': '2021-09', 'value': 3000.0},
 {'start_date': '2021-10', 'value': 2750.0},
 {'start_date': '2021-11', 'value': 19500.0}]

如果我的初始开始日期是 2021 年 5 月,我的结束日期是 2021 年 11 月,我现在可以实现吗?

我尝试了一些想法,但没有得到我需要的正确格式。

澄清:

我尝试创建一个日期和值为 0 的 dict,并与上面的 dict 进行比较,但格式错误,我不知道这是否是最好的方法:(它获取开始日期和结束日期,填补缺失的,初始日期是一个日期时间,但我的输出是一个只有月份的str)

end_date = job_start_date_end if job_start_date_end is not None else date.today()
if job_start_date_start:
    months_list = [
        dt.strptime('%2.2d-%2.2d' % (y, m), '%Y-%m').strftime('%Y-%m')
        for y in range(job_start_date_start.year, end_date.year + 1)
        for m in range(
            job_start_date_start.month if y == job_start_date_start.year else 1,
            end_date.month + 1 if y == end_date.year else 13
        )
    ]
    month_dict = {key: 0 for key in months_list}
else:
    month_dict = None
result = {**month_dict, **my_incomplete_dict}

这得到了我想要的,但不是我需要的格式,输出是:

{'2021-05': 0, '2021-06': 0}

我不知道它是否有用,但我的前端需要(用于图表)的最终输出是:

{
  "chartlabels": [
    "2020-05",
    "2021-06",
    "2021-07",
    "2021-08",
    "2021-09"
  ],
  "chartvalues": [
    1500,
    0,
    0,
    2750,
    19500
  ]
}

我已经这样做了,但没有缺少的月份。

【问题讨论】:

  • 我不明白你要做什么,也不明白你的问题是什么(可能是因为你没有问)。
  • 不确定我是否正确,但您确定要使用字典列表吗?也许您应该只使用字典,其中对于每个条目,键是日期,值是您的“值”字段。
  • I tried some ideas, but didn't get the correctly format I need. 包含您尝试过的一些想法,将对我们有所帮助。包括您需要的“正确格式”也对我们有很大帮助。
  • @Ben 我以这种方式接收数据,我的最终输出不同(我编辑了问题以便更好地澄清)。最后,我想要的是缺少月份的最终输出格式。我已经转换为我的最终输出,但没有缺少几个月。而且我的初始字典可以有多个元素具有相同的年月,然后我 group_by 也(具有相同的初始格式)
  • @mkrieger1 抱歉,我编辑了问题以便更好地澄清,并附有我想要的示例。我的问题是以与我最初的字典列表相同的格式用'value': 0 填充缺失的月份。但也可能是我的最终输出格式(缺少值)。

标签: python python-3.x date


【解决方案1】:

我不完全确定您在寻找什么,但这可能就是您正在寻找的。​​p>

dictlist = [{'start_date': '2020-11', 'value': 1500.0}, {'start_date': '2021-08', 'value': 6000.0}, {'start_date': '2021-09', 'value': 3000.0}, {'start_date': '2021-10', 'value': 2750.0}, {'start_date': '2021-11', 'value': 19500.0}]

for year in list(set([d['start_date'].split('-')[0] for d in dictlist])):
    for month in range(1,13):
        monthstr = str(month).zfill(2)
        if not any(d['start_date'] == f"{year}-{monthstr}" for d in dictlist):
            dictlist.append({'start_date': f"{year}-{monthstr}", "value": 0})

newlist = sorted(dictlist, key=lambda d: d['start_date']) 

【讨论】:

  • 谢谢。我尝试了类似的方法(但格式错误,我会看看是否可以将您的解决方案与我的解决方案一起使用),但问题是,我不想要一整年。我编辑了这个问题以便更好地澄清。
  • 我将您的答案与我尝试过的代码一起使用,它有效,谢谢!我正在等待评论发布完整的答案。
【解决方案2】:

这是完整的答案,它将提供我想要的数据,用值 0 填充缺失的月份。 这将用作 FastAPI 响应。

start_date = job_start_date_start if job_start_date_start is not None \
    else dt.strptime(result[0].get("start_date"), '%Y-%m')
end_date = job_start_date_end if job_start_date_end is not None else date.today()
months_list = [dt.strptime('%2.2d-%2.2d' % (y, m), '%Y-%m').strftime('%Y-%m')
                for y in range(start_date.year, end_date.year + 1)
                for m in range(start_date.month if y == start_date.year else 1,
                                end_date.month + 1 if y == end_date.year else 13)]
for yearmonth in months_list:
    if not any(d['start_date'] == f"{yearmonth}" for d in result):
        result.append({'start_date': f"{yearmonth}", "value": 0})
result = sorted(result, key=lambda d: d['start_date'])
# Change the format to my desired output
value_list = [result[value].get("value") for value in range(len(result))]
start_date_list = [result[value].get("start_date") for value in range(len(result))]
result_dict = {"chartvalues": value_list, "chartlabels": start_date_list}
return result_dict

这将得到以下格式:

{
  "chartlabels": [
    "2020-05",
    "2021-06",
    "2021-07",
    "2021-08",
    "2021-09"
  ],
  "chartvalues": [
    1500,
    0,
    0,
    2750,
    19500
  ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    相关资源
    最近更新 更多