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

332
Visualizações
¿Cómo filtrar la lista de diccionarios en python?

Tengo una lista de diccionarios que es la siguiente:

 VehicleList = [ { 'id': '1', 'VehicleType': 'Car', 'CreationDate': datetime.datetime(2021, 12, 10, 16, 9, 44, 872000) }, { 'id': '2', 'VehicleType': 'Bike', 'CreationDate': datetime.datetime(2021, 12, 15, 11, 8, 21, 612000) }, { 'id': '3', 'VehicleType': 'Truck', 'CreationDate': datetime.datetime(2021, 9, 13, 10, 1, 50, 350095) }, { 'id': '4', 'VehicleType': 'Bike', 'CreationDate': datetime.datetime(2021, 12, 10, 21, 1, 00, 300012) }, { 'id': '5', 'VehicleType': 'Car', 'CreationDate': datetime.datetime(2021, 12, 21, 10, 1, 50, 600095) } ]

¿Cómo puedo obtener una lista de los vehículos más recientes para cada 'Tipo de vehículo' según su 'Fecha de creación'?

Espero algo como esto-

 latestVehicles = [ { 'id': '5', 'VehicleType': 'Car', 'CreationDate': datetime.datetime(2021, 12, 21, 10, 1, 50, 600095) }, { 'id': '2', 'VehicleType': 'Bike', 'CreationDate': datetime.datetime(2021, 12, 15, 11, 8, 21, 612000) }, { 'id': '3', 'VehicleType': 'Truck', 'CreationDate': datetime.datetime(2021, 9, 13, 10, 1, 50, 350095) } ]

Intenté separar cada diccionario según su 'Tipo de vehículo' en diferentes listas y luego elegir el último.

Creo que podría haber una forma más óptima de hacer esto.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Use un mapeo de diccionario desde el valor de VehicleType hasta el diccionario que desea en su lista final. Compare la fecha de cada elemento en la lista de entrada con la de su dictamen y conserve la última.

 latest_dict = {} for vehicle in VehicleList: t = vehicle['VehicleType'] if t not in latest_dict or vehicle['CreationDate'] > latest_dict[t]['CreationDate']: latest_dict[t] = vehicle latestVehicles = list(latest_dict.values())
over 4 years ago · Santiago Trujillo Relatório

0

Aquí hay una solución usando max y filter :

 VehicleLatest = [ max( filter(lambda _: _["VehicleType"] == t, VehicleList), key=lambda _: _["CreationDate"] ) for t in {_["VehicleType"] for _ in VehicleList} ]

Resultado

 print(VehicleLatest) # [{'id': '2', 'VehicleType': 'Bike', 'CreationDate': datetime.datetime(2021, 12, 15, 11, 8, 21, 612000)}, {'id': '3', 'VehicleType': 'Truck', 'CreationDate': datetime.datetime(2021, 9, 13, 10, 1, 50, 350095)}, {'id': '5', 'VehicleType': 'Car', 'CreationDate': datetime.datetime(2021, 12, 21, 10, 1, 50, 600095)}]
over 4 years ago · Santiago Trujillo Relatório

0

Creo que puedes lograr lo que quieres usando la función groupby de itertools.

 from itertools import groupby # entries sorted according to the key we wish to groupby: 'VehicleType' VehicleList = sorted(VehicleList, key=lambda x: x["VehicleType"]) latestVehicles = [] # Then the elements are grouped. for k, v in groupby(VehicleList, lambda x: x["VehicleType"]): # We then append to latestVehicles the 0th entry of the # grouped elements after sorting according to the 'CreationDate' latestVehicles.append(sorted(list(v), key=lambda x: x["CreationDate"], reverse=True)[0])
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