在Python中进行timedelta操作时,从字典中更改多个键

时间:2015-06-10 06:28:59

标签: python dictionary

我有一个字典,键是整数。我随意将其中一个键更改为日期,我需要更改其他键。

示例数据:

{'C-STD-B&M-SUM': {datetime.date(2015, 7, 12): 0,
               -1: 0.21484699999999998,
               -2: 0.245074,
               -3: 0.27874}

预期产出:

{'C-STD-B&M-SUM': {datetime.date(2015, 7, 12): 0,
               datetime.date(2015, 7, 11): 0.21484699999999998,
               datetime.date(2015, 7, 10): 0.245074,
               datetime.date(2015, 7, 9): 0.27874}

目前的代码:

def change_start_date(dictionary_with_temporal_distribution):
    unsw_mid_year_end_date = datetime.date(2015, 7, 12)
    dictionary_with_temporal_distribution['C-STD-B&M-SUM'][unsw_mid_year_end_date] = dictionary_with_temporal_distribution['C-STD-B&M-SUM'][0]
    del dictionary_with_temporal_distribution['C-STD-B&M-SUM'][0]
    for k, v in dictionary_with_temporal_distribution['C-STD-B&M-SUM'].items():

2 个答案:

答案 0 :(得分:1)

你可以试试像 -

def change_start_date(dictionary_with_temporal_distribution):
    unsw_mid_year_end_date = datetime.date(2015, 7, 12)
    for k in list(dictionary_with_temporal_distribution['C-STD-B&M-SUM'].keys()):
        dictionary_with_temporal_distribution['C-STD-B&M-SUM'][unsw_mid_year_end_date + timedelta(days=k)] = dictionary_with_temporal_distribution['C-STD-B&M-SUM'][k]
        del dictionary_with_temporal_distribution['C-STD-B&M-SUM'][k]

答案 1 :(得分:0)

您可以使用dict理解语法并转换和替换键:

dct = {datetime.date(2015, 7, 12): 0,
    -1: 0.21484699999999998,
    -2: 0.245074,
    -3: 0.27874}

def offset(offset, base):
    """Applies an offset in days to a base date.
        If the offset is already a date it is returned as is."""
    if type(offset) == datetime.date:
        return offset
    return base + datetime.timedelta(offset)

def offset_keys(dct, base):
    """Takes a dict and runs offset(key, base) on all keys"""
    return { offset(k, base): v for k, v in dct.items() }

pprint(offset_keys(dct, datetime.date(2015, 7, 12)))
{datetime.date(2015, 7, 9): 0.27874,
 datetime.date(2015, 7, 10): 0.245074,
 datetime.date(2015, 7, 11): 0.21484699999999998,
 datetime.date(2015, 7, 12): 0}