python - How to create a dictionary where the keys are the elements in a list and the values are numbers from 1 to n? -
let's have list l1 = [a,b,c,d,e] , want map dictionary contain following {a:1, b:2, c:3, d:4, e:5}
i know how in naive way, more 'pythonic'
the naive way:
dic = {} j = 1 in list1: dic[i] = j j += 1
how using dictionary comprehension:
>>> {v: k k, v in enumerate(l1, 1)} {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Comments
Post a Comment