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)
Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value. Use map() to apply fn to each value of the list. Use zip() to pair original values to the values produced by fn .
To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements.
We can use the Python built-in function map() to apply a function to each item in an iterable (like a list or dictionary) and return a new iterator for retrieving the results. map() returns a map object (an iterator), which we can use in other parts of our program.
To map the list elements in Python, use the map() function.
In Python 3 you can use this dictionary comprehension syntax:
def foo(somelist): return {x[0]:x for x in somelist}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With