python - 在字典中过滤日期 - python

标签 python date dictionary

我有一本这样的字典:

> { "Country1": {"time": [1/22/20, 1/23/20...], "cases":[0,10,20,...]},
> "Country2": {"time": [1/22/20, 1/23/20...], "cases":[0,10,20,...]},
> .... }
我想删除高于给定日期的日期及其各自的情况。我试过这个,但它失败了,因为 IndexError: list index out of range。你会怎么做?
for i in (range(len(Country_Region))):
    for j in (range(len(Countries_Dict[i][Country_Region[i]]['time']))):
        if datetime.strptime(Countries_Dict[i][Country_Region[i]]['time'][j], '%m/%d/%y')  > datetime.strptime(date, '%m-%d-%y'):
            Countries_Dict[i][Country_Region[i]]['time'].pop(j)
            Countries_Dict[i][Country_Region[i]]['cases'].pop(j)
日期是字符串格式,所需的输出是与以前相同的字典,没有高于给定日期的日期及其各自的情况。

最佳答案

您的 IndexError可能是数据不一致的故障,timecases有不同的长度。
您可以使用 zip将它们聚集在一起剪裁在较小列表的长度上。

data = {
    'Country1': {
        'time': ['1/22/20', '1/23/20', '1/24/20', '1/25/20'],
        'cases': [0, 10, 20, 30, 40]   # Inconsistent data
    },
    'Country2': {
        'time': ['1/22/20', '1/23/20', '1/24/20', '1/25/20'],
        'cases': [0, 10, 20, 30]
    }
}

threshold_date = '1/23/20'


def parse_date(date):
    return datetime.strptime(date, '%m/%d/%y')


for country, country_data in data.items():
    pre_threshold = [
        (time, case)
        for time, case in zip(country_data['time'], country_data['cases'])
        if parse_date(time) <= parse_date(threshold_date)
    ]
    country_data['time'] = [t for t, c in pre_threshold]
    country_data['cases'] = [c for t, c in pre_threshold]
这将导致,
{'Country1': {'time': ['1/22/20', '1/23/20'], 'cases': [0, 10]},
 'Country2': {'time': ['1/22/20', '1/23/20'], 'cases': [0, 10]}}
请注意,第一个列表在 time 中有 4 对 5 条目。和 cases但没关系。
这是创建一个新列表,可以提高此代码的效率,但为了可读性,我保留了它。您可以根据需要选择这样做。

关于python - 在字典中过滤日期 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67130718/

相关文章:

MYSQL STR_TO_DATE 未返回所需结果

python - 为任何需要重复两次的东西写一个函数总是最好的主意吗?

python - 使用 VBox 的 Bokeh 小部件间距和对齐

python - 用于从图像中识别文本的简单 python 库

c++ 当前日期和指针问题!

mysql - 如何格式化MySQL查询日期

c++ - 何时检查项目是否已存在于 C++ 集合/映射中?

parsing - 在go中将字符串拆分为 map 的简单方法

python - 不可哈希类型 : 'list' in dictionary

python - 'obj'参数是如何传递给Django Rest Framework中的Permission类函数的?