Home > Blockchain >  Pythonic way to make a dictionary from lists of unequal length without padding Nones
Pythonic way to make a dictionary from lists of unequal length without padding Nones

Time:12-18

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?

CodePudding user response:

This dict-comprehension should do it:

rows = [row1, row2, row3, row4]
{k: v for v, row in enumerate(rows, 1) for k in row}
  • Related