Hi All,
I am trying to assign dynamically with dates as keys and values based up on the user input, but when i try to add the keys and values only the last values are getting populated. For example, For regular day 2022-04-12 to be a dict key and days and fare would be its values like below {'2022-04-12': ('Tuesday', 0.95)}
On the flip side, when tried to add the dict with old dates 05th April then i am expecting the output to be like below, but instead it will display only the second key and its values basically the keys and values not appending {'2022-04-12': ('Tuesday', 0.95), '2022-04-05': ('Tuesday', 0.95)}
import datetime
from datetime import date
import calendar
import pandas as pd
class Bus_Fare():
now = date.today()
week = calendar.day_name[now.weekday()]
_fare = 0.95
def __init__(self,count_sign=None):
self.Dict_of_days = {}
self.count_sign = count_sign
if self.count_sign == 'R':
Regular_day = self.Regular_day('Y')
for i,k in Regular_day.items():
self.Dict_of_days[i] = k
elif self.count_sign == 'P':
Previous_day = self.Previous_day('2022-04-05')
for i,k in Previous_day.items():
self.Dict_of_days[i] = k
def Regular_day(self,yes_or_no=None,date=now,day=week,fare=_fare):
self.date = date
self.day = day
self.fare = fare
init_dict = {}
if yes_or_no == 'Y':
init_dict[str(self.date)] = (self.day,self.fare)
else:
init_dict[str(self.date)] = (self.day,0)
return init_dict
def Previous_day(self,pre_date):
self.pre_date = pd.Timestamp(pre_date)
self.preweek = self.pre_date.day_name()
pre_day_update = self.Regular_day(yes_or_no='Y',date=self.pre_date.strftime('%Y-%m-%d'),day=self.preweek)
return pre_day_update
def display(self):
print(self.Dict_of_days)
Could you show also the part (or example) of how you are using this class? There’s couple of moving parts here and it isn’t clear how it’s intended to use it.
Here, with every call to the Regular_day method, a new init_dict{} dictionary is created. So, it seems to loose its previous values may be. Coz every time it is declared newly when this method is called.
One solution would be to declare init_dict{} globally so that it retains all its values that are added subsequently or to pass it as an argument from method to method if you are following strict functional programming paradigm.