Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda