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])
Advertisement
Answer
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.