Pass
enumerated
list to
dict
constructor
>>> items = ['a','b','c']>>> dict(enumerate(items, 1))>>> {1: 'a', 2: 'b', 3: 'c'}
Here
enumerate(items, 1)will yield
tuples of element and its index.
Indices will start from
1( note the second argument of
enumerate).
Using this expression you can define a function inline like:
>>> func = lambda x: dict(enumerate(x, 1))
Invoke it like:
>>> func(items)>>> {1: 'a', 2: 'b', 3: 'c'}
Or a regular function
>>> def create_dict(items): return dict(enumerate(items, 1))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)