Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change multiple keys from dictionary, while doing timedelta operation in Python

I have a dictionary, which the keys are integers. I arbitrarily changed one of the keys to a date, and I need to change the other keys.

Sample data:

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

Expected output:

{'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}

Current code so far:

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():
like image 660
Filipe Barreto Peixoto Teles Avatar asked Nov 10 '22 11:11

Filipe Barreto Peixoto Teles


1 Answers

You can try something like -

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]
like image 151
Anand S Kumar Avatar answered Nov 14 '22 21:11

Anand S Kumar