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

Replacing strings of weekdays ("MON", "TUE" etc.) in a list with the corresponding weekday numbers

I have the user select a strings of weekdays which then get stored in a list. My goal is to replace any user-selected strings with it’s corresponding weekday number. My code works but it seems unnecessarily bulky. Is there a more elegant way?

selected_weekdays = ["MON", "WED", "THU", "SAT"]

for i in range(len (selected_weekdays)):
    if selected_weekdays[i] == "MON":
        selected_weekdays[i] = 0
    elif selected_weekdays[i] == "TUE":
        selected_weekdays[i] = 1
    elif selected_weekdays[i] == "WED":
        selected_weekdays[i] = 2
    elif selected_weekdays[i] == "THU":
        selected_weekdays[i] = 3
    elif selected_weekdays[i] == "FRI":
        selected_weekdays[i] = 4
    elif selected_weekdays[i] == "SAT":
        selected_weekdays[i] = 5
    elif selected_weekdays[i] == "SUN":
        selected_weekdays[i] = 6
    else:
        pass

print(selected_weekdays)

Correct output:

[0, 2, 3, 5]

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

>Solution :

You can avoid some extra work by generating your dictionary mapping

it’s also better to avoid modifying a structure you’re also iterating over for a variety of reasons
See Modifying list while iterating

The dictionary .get() method will choose a default choice (weekday in your original case, though you may want to change this such that it’s one of

  • the unlisted weekday (this is what your code currently does, so I kept the results the same)
  • an Exception (KeyError from directly indexing [] .. you may want this to highlight errors)
  • None (essentially throws out bad values and is easy to filter in a next step)
# dictionary expression
weekday_mapping = {day: index for index, day in enumerate((
    "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"))}

selected_weekdays = ["MON", "WED", "THU", "SAT"]
results = []
for weekday in selected_weekdays:
    results.append(weekday_mapping.get(weekday, weekday))
>>> results
[0, 2, 3, 5]
>>> selected_weekdays = ["MON", "WED", "THU", "FakeDay", "SAT"]
...
>>> results
[0, 2, 3, 'FakeDay', 5]
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