Reputation: 909
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
wid_letter = ['C', 'A', 'B']
widgets_per_row = 10
wid_letter = wid_letter * widgets_per_row
#print("wid_letter : ", wid_letter, '\n')
ID = (list(range(1,widgets_per_row + 1,1)))
wid_type = []
# Make list of widget_letters to match length of widget ID
for i in ID:
wid_type.append(wid_letter[i-1])
print(len(wid_type))
# Turn the two lists into a dict
wid_ID_dict = dict(zip(ID, wid_type))
print('\n'*2, wid_ID_dict,'\n')
print("Widget_type: ", wid_ID_dict[1])
Upvotes: 1
Views: 43
Reputation: 563
wid = {i:w for i,w in enumerate(wid_letter[:widgets_per_row],1)}
Dict comprehension above may be your quest item, wid is wid_ID_dict in your code.
Upvotes: 0
Reputation: 2692
Instead of overriding your list, you can just use module
to get the index of letter you need. Then simple dictionary comprehension will do the job:
wid_letter = ['C', 'A', 'B']
widgets_per_row = 10
wid_ID_dict = {i + 1: wid_letter[i%len(wid_letter)] for i in range(widgets_per_row)}
Result would look like this:
{1: 'C', 2: 'A', 3: 'B', 4: 'C', 5: 'A', 6: 'B', 7: 'C', 8: 'A', 9: 'B', 10: 'C'}
Upvotes: 2
Reputation: 444
This leads to the same result, is this what you are looking for?
from itertools import cycle
wid_letter = ['C', 'A', 'B']
letter_cycle = cycle(wid_letter)
widgets_per_row = 10
wid_ID_dict = {i: next(letter_cycle) for i in range(1,widgets_per_row+1)}
print(wid_ID_dict)
Upvotes: 1