Map list onto dictionary

前端 未结 6 604
-上瘾入骨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:56

    If I understand your question correctly, I believe you can accomplish this with a combination of map, zip, and the dict constructor:

    def dictMap(f, xs) :
        return dict(zip(map(f, xs), xs)
    

    And a saner implementation :

    def dictMap(f, xs) :
        return dict((f(i), i) for i in xs)
    

提交回复
热议问题