Search code examples
pythonenumerate

How to pass 2 arguments to dict() built-in function?


How to pass 2 arguments to dict() built-in function? I want to put a function with one line of code using enumerate() function:

Given function:

def d_list(L):
    return dict(enumerate(L))

# call the function

print(d_list(['a','b','c']))

and the output was:

{0: 'a', 1: 'b', 2: 'c'}

and I want the output as:

{'a': 0, 'b': 1, 'c': 2}

Please, I want a fast answer!


Solution

  • Simply do the dict comprehension yourself.

    def d_list(L):
        return {val: idx for (idx, val) in enumerate(L)}