Skip to content Skip to sidebar Skip to footer

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',

Solution 1:

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

>>> defcreate_dict(items):
        returndict(enumerate(items, 1))

Solution 2:

If the keys are just the index of the element in the list, as in your example:

{i+1: x for i, x in enumerate(mylist)}

Solution 3:

Iterate through the list and assign every value to a number (starting from 1).

deflist_to_dict(items):
    return {n + 1: items[n] for n inrange(len(items))}

Replace n + 1 with n if you want the dictionary to start from zero.

Post a Comment for "Creating A Function That Can Convert A List Into A Dictionary In Python"