2025年6月14日 星期六

defaultdict sample II

 from collections import defaultdict

dates = ["2024-01-01", "2024-01-15", "2024-02-01", "2024-02-15",'2025-06-12','2025-06-14']

monthly_data = defaultdict(list)

yearly_data = defaultdict(list)


for date in dates:

  year = date[:4]

  month = date[:7]

  monthly_data[month].append(date)

  yearly_data[year].append(date)


for i in dict(yearly_data).items():

  print(i)

print()

for i in dict(monthly_data).items():

  print(i)

  

Output:


('2024', ['2024-01-01', '2024-01-15', '2024-02-01', '2024-02-15'])

('2025', ['2025-06-12', '2025-06-14'])


('2024-01', ['2024-01-01', '2024-01-15'])

('2024-02', ['2024-02-01', '2024-02-15'])

('2025-06', ['2025-06-12', '2025-06-14'])

沒有留言:

張貼留言