Creating a function that can convert a list into a dictionary in python
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 todict
constructor>>> items = ['a','b','c'] >>> dict(enumerate(items, 1)) >>> {1: 'a', 2: 'b', 3: 'c'}
Here
enumerate(items, 1)
will yieldtuple
s of element and its index.
Indices will start from1
( 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))