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

145
Visualizações
Python create Ordered Dict with 30 most recent day keys

Hello I'm writing a Django application that reports on daily items purchased. I want to organize the data in a dictionary structure like so..

monthly_items = {
    "Apr-27" : [ list of objects purchased on April-27th ]
    "Apr-26" : [ list of objects purchased on April-26th ]
    "Apr-25" : [ list of objects purchased on April-25th ]
    "Apr-24" : [ list of objects purchased on April-24th ]
    ... 
    "Mar-27" : [ list of objects purchased on March-27th ]
}

right now my code looks like this (start_date and end_date are configured for last month and today, respectively):

month_dict = {
    1: 'Jan',
    2: 'Feb',
    3: 'Mar',
    4: 'Apr',
    5: 'May',
    6: 'June',
    7: 'July',
    8: 'Aug',
    9: 'Sept',
    10: 'Oct',
    11: 'Nov',
    12: 'Dec',
}

from collections import OrderedDict
monthly_items = OrderedDict()

# pull items from last 30 days
items = Item.objects.filter(create_date__gte=start_date, create_date__lt=end_date).order_by('-create_date')

for item in items:
    day = str(month_dict.get(item.create_date.month)) + '-' + str(item.create_date.day)
    day_items = monthly_items.get(day, [])
    day_items.append(item)

this works great, and I get the dictionary structure that I want, but my problem is that if there are no items purchased on April 24th, there will be no key in the dictionary, and when I print my dict to html, I am missing a Apr-24 column when in reality, I want one but with an empty list. Is there a way to pre-populate an ordered dict with the 30 most recent days as keys (with compatibility to cross months)?

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