Home > Blockchain >  Python for loop over dictionary stops after first match with IF statement
Python for loop over dictionary stops after first match with IF statement

Time:01-07

Trying to write a simple script to determine the moon name for the date. I have a dictionary of dates and moon names and tried to iterate over each to compare today's date to the date of the full moon, expecting that the last match would win, but it seems Python stops after the first match.

#!/usr/bin/python3

from datetime import date

def get_moon_name(d):
    full_moons = {
      '2022-12-07': 'Able',
      '2023-01-06': 'Baker',
      '2023-02-05': 'Charlie',
      '2023-03-07': 'Delta' }

    for md in full_moons.keys():
        moon_date = date.fromisoformat(md)
        print(f"Comparing {d} to {moon_date}")
        if d >= moon_date:
            moon_name = full_moons[md]
        return moon_name

if __name__ == "__main__":
    d_today = date.today()
    print(f"This full moon's name is {get_moon_name(d_today)}")

Removing the first date will yield Baker as the moon name, so it would match on that if it could get to it.

This is either Python 3.9.6 (Mac OS) or 3.10.9 (Homebrew).

Thoughts? I'm sure there is a more Pythonic way, but I don't see why this fails.

Shorthand: Tried running this, expected it to output Baker as today is 6 January, but instead I get Able and no indication that it ever looked at the second value.

CodePudding user response:

The return statement will break your for loop after the first match, so always you will get Able as an answer. Try this instead :

from datetime import date


def get_moon_name(d):
    full_moons = {
      '2022-12-07': 'Able',
      '2023-01-06': 'Baker',
      '2023-02-05': 'Charlie',
      '2023-03-07': 'Delta' }

    for md in full_moons.keys():
        moon_date = date.fromisoformat(md)
        print(f"Comparing {d} to {moon_date}")
        if d >= moon_date:
            moon_name = full_moons[md]
    
    return moon_name

if __name__ == "__main__":
    d_today = date.today()
    print(f"This full moon's name is {get_moon_name(d_today)}");
  • Related