Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map list onto dictionary

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)

like image 447
Jeffrey Aylesworth Avatar asked Jan 03 '10 03:01

Jeffrey Aylesworth


People also ask

How do I map a dictionary to a list?

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 .

Can you put a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements.

Can I use map on dictionary Python?

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.

Can I map a list in Python?

To map the list elements in Python, use the map() function.


1 Answers

In Python 3 you can use this dictionary comprehension syntax:

def foo(somelist):     return {x[0]:x for x in somelist} 
like image 56
Htechno Avatar answered Sep 25 '22 07:09

Htechno