Map list onto dictionary

前端 未结 6 614
-上瘾入骨i
-上瘾入骨i 2021-02-02 08:14

Is there a way to map a list onto a dictionary? What I want to do is give it a function that will return the name of a key, and the value will be the original value. For example

6条回答
  •  暖寄归人
    2021-02-02 08:53

    I don't think a standard function exists that does exactly that, but it's very easy to construct one using the dict builtin and a comprehension:

    def somefunction(keyFunction, values):
        return dict((keyFunction(v), v) for v in values)
    
    print somefunction(lambda a: a[0], ["hello", "world"])
    

    Output:

    {'h': 'hello', 'w': 'world'}
    

    But coming up with a good name for this function is more difficult than implementing it. I'll leave that as an exercise for the reader.

提交回复
热议问题