Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update the values of a month's dictionary based on the current month – PYTHON3

I have a dictionary as shown below.

months_dict = {"m1":"JAN", "m2":"FEB", "m3":"MAR", "m4":"APR", "m5":"MAY", "m6":"JUN",
               "m7":"JUL", "m8":"AUG", "m9":"SEP", "m10":"OCT", "m11":"NOV", "m12":"DEC"}

Which I would like to update with last 12 months as shown below.

Expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

current_month_dict = {"m1":"MAR", "m2":"APR", "m3":"MAY", "m4":"JUN", "m5":"JUL", "m6":"AUG",
                      "m7":"SEP", "m8":"OCT", "m9":"NOV", "m10":"DEC","m11":"JAN","m12":"FEB"}

My try:

from datetime import datetime
current_month_text_3 = datetime.now().strftime('%h').upper()

I am stuck after that. I tried a lot by looping over the dictionary and creating a static month list and all. Could not figure out correct logic.

>Solution :

Looks like this is what you are looking for m1 here is the next month as i started the loop from i=1 you can do a i=0 to get m1 as feb

from datetime import datetime

arr_months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']


def transform_month_list(month_list):
    current_month_text_3 = datetime.now().strftime('%h').upper()
    idx = arr_months.index(current_month_text_3)
    for i in range(1, 13):
        month_list["m" + str(i)] = arr_months[(idx + i) % 12]


default_months_dict = {"m1": "JAN", "m2": "FEB", "m3": "MAR", "m4": "APR", "m5": "MAY", "m6": "JUN",
                   "m7": "JUL", "m8": "AUG", "m9": "SEP", "m10": "OCT", "m11": "NOV", "m12": "DEC"}


if __name__ == '__main__':
    try:
        transform_month_list(default_months_dict)
        print(default_months_dict)
    except Exception as e:
        print(e)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading