I've been struggling with how to loop through a list, adding 0 for the missing months back in to the original dictionary. I am thinking to create a list of months, from calendar
, loop through each of those, then loop through each month in my data...but can't quite figure out how to update the dictionary when there's a missing month in correct order.
import calendar
my_dict = {'Green Car':
[('January', 340),
('February', 2589),
('March', 12750),
('April', 114470),
('July', 4935),
('August', 1632),
('September', 61),
('December', 3409)],
'Red Truck':
[('January', 2325185),
('February', 209794),
('March', 201874),
('April', 19291),
('May', 18705),
('July', 22697),
('August', 22796)],
'Police Car':
[('January', 2037),
('February', 2620),
('March', 1480),
('April', 15630),
('July', 40693),
('August', 2329)],
'Zamboni':
[('January', 256),
('February', 426690),
('March', 589),
('April', 4740),
('May', 880),
('July', 1016),
('August', 106),
('September', 539),
('October', 598),
('November', 539),
('December', 470)],
'Witch Broom':
[('February', 350),
('March', 3520),
('October', 2703),
('November', 2221),
('December', 664)]
}
def fill_months(reported_months):
const_months = list(calendar.month_name)
x = 0
print("Looking for months in", reported_months)
# print(const_months)
for const_month in const_months:
for month in reported_months:
if const_month != month[0] and len(const_month) > 0:
print(const_month, month[0])
print("You don't have", const_month, "in the months group:", reported_months)
def main():
for commod, months in my_dict.items():
# print(commod)
# print(commod, months)
fill_months(months)
if __name__ == '__main__':
main()
For each key ("Green Car", "Red Truck", etc.) I want to loop through and add in a missing moth with the value 0
. So the "Green Car" in the end would turn out to be:
my_dict = {'Green Car':
[('January', 340),
('February', 2589),
('March', 12750),
('April', 114470),
('May', 0),
('June', 0),
('July', 4935),
('August', 1632),
('September', 61),
('October', 0),
('November', 0),
('December', 3409)],
I'm getting somewhere with this - but the logic feels kind of kludgy:
def fill_months(reported_months):
const_months = list(calendar.month_name)
x = 0
temp_months = []
for i in reported_months:
temp_months.append(i[0])
print("Looking for months in", reported_months)
# print(const_months)
for const_month in const_months:
if len(const_month) > 0:
if const_month not in temp_months:
reported_months.insert(x-1, (const_month, 0))
x += 1
print(reported_months)