pythonlistfunctiondictionarypython-holidays

Use Python Holidays package to get dates of holidays based on holiday names


I have this list of holidays

["New Year's Day",
 'Martin Luther King Jr. Day',
 'Memorial Day',
 'Independence Day',
 'Labor Day',
 'Thanksgiving',
 'Christmas Day',
 "New Year's Day (Observed)",
 'Martin Luther King Jr. Day (Observed)',
 'Memorial Day (Observed)',
 'Independence Day (Observed)',
 'Labor Day (Observed)',
 'Thanksgiving (Observed)',
 'Christmas Day (Observed)']

And would like to convert it to a dictionary where the keys are the dates of the holidays and the values are the holiday names. I need this to be dynamic so that it could return the dates of these holidays for any year. I know that the holiday library allows you to generate the dates and names of holidays for any given year like so:

holidays_US = []
for name, date in holidays.US(years=2022).items():
    print(name, date)
2022-01-01 New Year's Day
2022-01-17 Martin Luther King Jr. Day
2022-02-21 Washington's Birthday
2022-05-30 Memorial Day
2022-06-19 Juneteenth National Independence Day
2022-06-20 Juneteenth National Independence Day (Observed)
2022-07-04 Independence Day
2022-09-05 Labor Day
2022-10-10 Columbus Day
2022-11-11 Veterans Day
2022-11-24 Thanksgiving
2022-12-25 Christmas Day
2022-12-26 Christmas Day (Observed)

But I would like to reverse engineer this process by taking my list of holiday names as input and outputting the dates of those holidays.


Solution

  • To filter the holidays with your list you can use this example:

    import holidays
    
    YEAR = 2022
    
    my_list = [
        "New Year's Day",
        "Martin Luther King Jr. Day",
        "Memorial Day",
        "Independence Day",
        "Labor Day",
        "Thanksgiving",
        "Christmas Day",
        "New Year's Day (Observed)",
        "Martin Luther King Jr. Day (Observed)",
        "Memorial Day (Observed)",
        "Independence Day (Observed)",
        "Labor Day (Observed)",
        "Thanksgiving (Observed)",
        "Christmas Day (Observed)",
    ]
    
    # to speed up the search
    my_set = set(my_list)
    
    filtered_holidays = {
        k: v for k, v in holidays.US(years=YEAR).items() if v in my_set
    }
    
    print(filtered_holidays)
    

    Prints:

    {
        datetime.date(2022, 1, 1): "New Year's Day",
        datetime.date(2022, 1, 17): "Martin Luther King Jr. Day",
        datetime.date(2022, 5, 30): "Memorial Day",
        datetime.date(2022, 7, 4): "Independence Day",
        datetime.date(2022, 9, 5): "Labor Day",
        datetime.date(2022, 11, 24): "Thanksgiving",
        datetime.date(2022, 12, 25): "Christmas Day",
        datetime.date(2022, 12, 26): "Christmas Day (Observed)",
    }