简体   繁体   中英

how to change date format(Key) in python dictionary

days = {1:"MON", 2:"TUE", 3:"WED", 4:"THU", 5:"FRI", 6:"SAT", 7:"SUN"}

create a new dictionary like:

days_formated = {2:"MON", 3:"TUE", 4:"WED", 5:"THU", 6:"FRI", 7:"SAT", 1:"SUN"}
days = {1:"MON", 2:"TUE", 3:"WED", 4:"THU", 5:"FRI", 6:"SAT", 7:"SUN"}

days_formated = {k % 7 + 1: days[k] for k in days}

print(days_formated)

Prints:

{2: 'MON', 3: 'TUE', 4: 'WED', 5: 'THU', 6: 'FRI', 7: 'SAT', 1: 'SUN'}

You may do math operation nb % 7 + 1

7 -> %7 = 0 -> +1 = 1
1 -> %7 = 1 -> +1 = 2  

result = {k % 7 + 1: v for k, v in days.items()}
print(result)  # {2: "MON", 3: "TUE", 4: "WED", 5: "THU", 6: "FRI", 7: "SAT", 1: "SUN"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM