Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort data by mm/yyyy?

Tags:

python

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?

like image 956
user17807431 Avatar asked Jan 24 '23 04:01

user17807431


2 Answers

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})
like image 196
Mark Avatar answered Feb 04 '23 09:02

Mark


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)
like image 29
BrokenBenchmark Avatar answered Feb 04 '23 09:02

BrokenBenchmark