Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
How to sort data by mm/yyyy?

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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})
over 4 years ago · Santiago Trujillo Report

0

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!