I have a list of ‘widget types’, [“C”,”A”,”B”] and need to make a dict for those types to correspond to their respective ID’s, 1=’C’, 2=’A’, 3 = ‘B’, 4= ‘C’, 5=’A’, 6= ‘B’, 7 = ‘C’, etc. I already know how to do it, I just wondered if there was a more elegant pythonic way of achieving it than that below, also it would be good to have the length of the dict/lists expandable, i.e. in the example it is 10 but in reality it would be many hundreds of widgets long.
Existing working code
JavaScript
x
21
21
1
wid_letter = ['C', 'A', 'B']
2
widgets_per_row = 10
3
wid_letter = wid_letter * widgets_per_row
4
#print("wid_letter : ", wid_letter, 'n')
5
6
7
8
ID = (list(range(1,widgets_per_row + 1,1)))
9
wid_type = []
10
11
# Make list of widget_letters to match length of widget ID
12
for i in ID:
13
wid_type.append(wid_letter[i-1])
14
print(len(wid_type))
15
16
# Turn the two lists into a dict
17
wid_ID_dict = dict(zip(ID, wid_type))
18
print('n'*2, wid_ID_dict,'n')
19
20
print("Widget_type: ", wid_ID_dict[1])
21
Advertisement
Answer
JavaScript
1
2
1
wid = {i:w for i,w in enumerate(wid_letter[:widgets_per_row],1)}
2
Dict comprehension above may be your quest item, wid is wid_ID_dict in your code.