Check list item is present in Dictionary

2024/10/10 2:17:29

I'm trying to extend Python - Iterate thru month dates and print a custom output and add an addtional functionality to check if a date in the given date range is national holiday, print "NH" and that corresponding date.

Ex: 2020-05-04 & 2020-05-14 are national holidays and that date alone should be printed like enter image description here

import sys
from datetime import date, datetime, timedeltayear = int(sys.argv[1])
month = int(sys.argv[2])
st_dt = int(sys.argv[3])
en_dt = int(sys.argv[4])
public_holiday = sys.argv[5].split(',')ph = []
for d in public_holiday:ph.append(date(year, month, int(d)))def daterange(startDate, endDate, delta=timedelta(days=1)):currentDate = startDatewhile currentDate <= endDate:yield currentDatecurrentDate += deltaallDays = {}
_lastDayType = Nonefor dte in daterange(date(year, month, st_dt), date(year, month, en_dt), delta=timedelta(days=1)):#print(f"sdfdsfsdf:  {dte.weekday()}")if dte.weekday() < 5:_dayType = 'working'else:_dayType = 'weekend'_weeknum = dte.strftime("%V")_key = (_weeknum, _dayType)if _key not in allDays:allDays[_key] = []allDays[_key].append(dte)for k,v in allDays.items():week_end = ''gov_hol = ''if len(v) == 1:first, last = v[0], v[0]elif len(v) == 2 and k[1] == 'weekend':first, last, week_end = v[0], v[-1], 'YES'elif ph in allDays.values():gov_hol, first, last = 'NH', v[0], v[0]else:first, last = v[0], v[-1]print(f"{gov_hol}, {first} >> {last} >> {len(v)} >> {week_end}")

Input args: date.py 2020 5 1 31 "4, 14"

Currently, elif ph in allDays.values(): is not matching condition.

Current Output

2020-05-01 >> 2020-05-01 >> 1 >>  >> 
2020-05-02 >> 2020-05-03 >> 2 >> YES >> 
2020-05-04 >> 2020-05-08 >> 5 >>  >> 
2020-05-09 >> 2020-05-10 >> 2 >> YES >> 
2020-05-11 >> 2020-05-15 >> 5 >>  >> 
2020-05-16 >> 2020-05-17 >> 2 >> YES >> 
2020-05-18 >> 2020-05-22 >> 5 >>  >> 
2020-05-23 >> 2020-05-24 >> 2 >> YES >> 
2020-05-25 >> 2020-05-29 >> 5 >>  >> 
2020-05-30 >> 2020-05-31 >> 2 >> YES >> 

3rd column: number of days 4th column : prints "YES" if its a weekend

Answer

In general, everything you want the dates to be grouped by needs to be added to the dictionary keys:

year, month, st_dt, en_dt, public_holiday = 2020, 5, 1, 31, (4, 14)ph = []
for d in public_holiday:ph.append(date(year, month, int(d)))def daterange(startDate, endDate, delta=timedelta(days=1)):currentDate = startDatewhile currentDate <= endDate:yield currentDatecurrentDate += deltaallDays = {}
_lastDayType = Nonefor dte in daterange(date(year, month, st_dt), date(year, month, en_dt), delta=timedelta(days=1)):if dte.weekday() < 5:_dayType = 'working'else:_dayType = 'weekend'_hol = dte in ph                   # True or False_weeknum = dte.strftime("%V")_key = (_weeknum, _dayType, _hol)  # make unique rows!if _key not in allDays:allDays[_key] = []allDays[_key].append(dte)for k,v in allDays.items():week_end = ''gov_hol = k[-1]if len(v) == 1:first, last = v[0], v[0]elif len(v) == 2 and k[1] == 'weekend':first, last, week_end = v[0], v[-1], 'YES'else:first, last = v[0], v[-1]print(f"{gov_hol}, {first} >> {last} >> {len(v)} >> {week_end}")

Output:

False, 2020-05-01 >> 2020-05-01 >> 1 >> NO
False, 2020-05-02 >> 2020-05-03 >> 2 >> YES
True, 2020-05-04 >> 2020-05-04 >> 1 >> NO
False, 2020-05-05 >> 2020-05-08 >> 4 >> NO
False, 2020-05-09 >> 2020-05-10 >> 2 >> YES
False, 2020-05-11 >> 2020-05-15 >> 4 >> NO
True, 2020-05-14 >> 2020-05-14 >> 1 >> NO
False, 2020-05-16 >> 2020-05-17 >> 2 >> YES
False, 2020-05-18 >> 2020-05-22 >> 5 >> NO
False, 2020-05-23 >> 2020-05-24 >> 2 >> YES
False, 2020-05-25 >> 2020-05-29 >> 5 >> NO
False, 2020-05-30 >> 2020-05-31 >> 2 >> YES
https://en.xdnf.cn/q/118509.html

Related Q&A

a list of identical elements in the merge list

I need to merge the list and have a function that can be implemented, but when the number of merges is very slow and unbearable, I wonder if there is a more efficient way Consolidation conditions:Sub-…

How To Get A Contour Of More/Less Of The Expected Area In OpenCV Python

I doing some contour detection on a image and i want to find a contour based on a area that i will fix in this case i want the contour marked in red. So i want a bounding box around the red contour Fol…

Storing output of SQL Query in Python Variable

With reference to this, I tried modifying my SQL query as follows:query2 ="""insert into table xyz(select * from abc where date_time > %s and date_time <= ( %s + interval 1 hour))&…

file modification and creation

How would you scan a dir for a text file and read the text file by date modified, print it to screen having the script scan the directory every 5 seconds for a newer file creadted and prints it. Is it …

How to share a file between modules for logging in python

I wanted to log messages from different module in python to a file. Also I need to print some messages to console for debugging purpose. I used logger module for this purpose . But logger module will l…

Dont understand how this example one-hot code indexes a numpy array with [i,j] when j is a tuple?

I dont get how the line: results[i, sequence] = 1 works in the following.I am following along in the debugger with some sample code in a Manning book: "Deep Learning with Python" (Example 3.5…

convert nested list to normal list using list comprehension in python [duplicate]

This question already has answers here:How do I make a flat list out of a list of lists?(32 answers)Flatten an irregular (arbitrarily nested) list of lists(54 answers)Closed 6 years ago.How can I do t…

Transformation of pandas DataFrame adds a blank row

My original question was posted here. I have a dataframe as follows:ID START END SEQ 1 11 12 1 1 14 15 3 1 13 14 2 2 10 14 1 3 11 15 1 3 16 17 …

How to find a element after a search click checkbox in selenium Python

After I search for a user in the search field, I get the user I searched Now I need to select this user that shown in the list I tried with xpath and did not find the element ! could you help ? So aft…

Running parameterized queries

Quite new to this google bigquery sql thing so please bear with me. Im trying to build a google standardSQL parameterized query. The following sample was used and ran successfully on Google BigQuery We…