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

174
Vistas
Pythonic way to make a dictionary from lists of unequal length without padding Nones

I have a list of 'Id's' that I wish to associate with a property from another list, their 'rows'. I have found a way to do it by making smaller dictionaries and concatenating them together which works, but I wondered if there was a more pythonic way to do it?

Code

row1 = list(range(1, 6, 1))
row2 = list(range(6, 11, 1))
row3 = list(range(11, 16, 1))
row4 = list(range(16, 21, 1))

row1_dict = {}
row2_dict = {}
row3_dict = {}
row4_dict = {}

for n in row1:
    row1_dict[n] = 1
for n in row2:
    row2_dict[n] = 2
for n in row3:
    row3_dict[n] = 3
for n in row4:
    row4_dict[n] = 4

id_to_row_dict = {}
id_to_row_dict = {**row1_dict, **row2_dict, **row3_dict, **row4_dict}
print('\n')
for k, v in id_to_row_dict.items():
    print(k, " : ", v)

Output of dictionary which I want to replicate more pythonically

1  :  1
2  :  1
3  :  1
4  :  1
5  :  1
6  :  2
7  :  2
8  :  2
9  :  2
10  :  2
11  :  3
12  :  3
13  :  3
14  :  3
15  :  3
16  :  4
17  :  4
18  :  4
19  :  4
20  :  4

Desired output

Same as my output above, I just want to see if there is a better way to do it?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

This dict-comprehension should do it:

rows = [row1, row2, row3, row4]
{k: v for v, row in enumerate(rows, 1) for k in row}
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