Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda