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:
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.
CodePudding user response:
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)
CodePudding user response:
Use such syntax
{ modify_func(key) : val for key, val in months_dict.items()}
In you case
>>> { f"m{(int(key[1:]) 9) % 12 1}" : val for key, val in months_dict.items()}
{'m11': 'JAN', 'm12': 'FEB', 'm1': 'MAR', 'm2': 'APR', 'm3': 'MAY', 'm4': 'JUN', 'm5': 'JUL', 'm6': 'AUG', 'm7': 'SEP', 'm8': 'OCT', 'm9': 'NOV', 'm10': 'DEC'}