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

Python Loop over a Dictionary until i went over x elements

Hey i have a Short Question:

I Wanted to Iterate over my Dictionary with 7 Elements inside (Days of the Week)

and wanted to start at x element and loop until i went x elements forward
i thought about a while loop and manually set the current element to the start when reaching the end.

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

        while x in days_dict:
            final_day = days_dict[x]
            x += 1
            print(final_day)
        


What would be the best way to go about looping until you went x steps?

My Dictionary Looks like this:

days_dict = {"Monday":0, "Tuesday":1, "Wednesday":2, "Thursday":3, "Friday":4, "Saturday":5, "Sunday":6}



Desired Output for y = 1 and x = 9:
Thursday or 3

>Solution :

First of all, you can’t use an integer to access a dictionary element when the index is a string. You need to swap the index and values: day_dict = {0:'Monday', 1:'Tuesday'...}

Rather than loop, just perform the calculation directly: final_day = day_dict[(y+x) % len(day_dict)]

Anyone else can correct me if I’m wrong – I’m only human

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