Map list onto dictionary

Jeffrey Aylesworth picture Jeffrey Aylesworth · Jan 3, 2010 · Viewed 49.7k times · Source

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;

somefunction(lambda a: a[0], ["hello", "world"])
=> {"h":"hello", "w":"world"}

(This isn't a specific example that I want to do, I want a generic function like map() that can do this)

Answer

Htechno picture Htechno · Jan 3, 2010

In Python 3 you can use this dictionary comprehension syntax:

def foo(somelist):
    return {x[0]:x for x in somelist}