Creating a function that can convert a list into a dictionary in python

Creating a function that can convert a list into a dictionary in python,第1张

Creating a function that can convert a list into a dictionary in python

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
tuple
s 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))


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5632422.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存