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

发布于 2021-01-29 15:04:48

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?

关注者
0
被浏览
66
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看