Hello I am new to python, if I have a txt.file like so
23/3/2020 12
7/7/2020 15
25/1/2020 16
14/2/2020 12
12/3/2020 19
1/11/2020 11
16/6/2020 20
14/3/2020 13
13/11/2020 20
(all of them are strings)and I want to turn it into a dict() with mm/yyyy as the key and the sum of the numbers on the same month as value, what should I do?
I would recommend just using Python's builtin datetime parsing and collections.counter for this. Essentially, parse the dates and add the count to the counter.
from collections import Counter
from datetime import datetime
counts = Counter()
with open(path) as f:
for date, count in map(str.split, f):
date = datetime.strptime(date, '%d/%m/%Y')
counts[date.month, date.year] += int(count)
counts
The result is a dict with month-year tuples and totals:
Counter({(3, 2020): 44,
(7, 2020): 15,
(1, 2020): 16,
(2, 2020): 12,
(11, 2020): 31,
(6, 2020): 20})
The following code snippet takes in the file, reads in one line at a time, and maintains counters for each month/year
combination seen so far:
month_counters = {}
with open('test.txt', 'r') as input_file:
lines = input_file.readlines()
for line in lines:
[date, num] = line.split()
month_and_year = date[date.index("/") + 1:]
if month_and_year in month_counters:
month_counters[month_and_year] += int(num)
else:
month_counters[month_and_year] = int(num)
print(month_counters)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With