当前位置: 首页 > 面试题库 >

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

孙承
2023-03-14
问题内容

I’m trying to create a function that will convert a given list into a given
dictionary (where I can specify/assign values if I want).

So for instance, if I have a list

['a', 'b', 'c', ..., 'z']

and I want to convert to a dictionary like this

{1: 'a', 2: 'b', 3: 'c', ..., 26: 'z'}

I know how to do this using a dictionary comprehension

{num : chr(96 + num) for num in range(1, 26)}

but I can’t figure out how to make this into a more generalized function that
would be able to turn any list into a dictionary. What’s the best approach
here?


问题答案:

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


 类似资料:

相关阅读

相关文章

相关问答