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)
If you want a general function to do this, then you're asking almost the right question. Your example doesn't specify what happens when the key function produces duplicates, though. Do you keep the last one? The first one? Do you actually want to make a list of all the words that start with the same letter? These questions are probably best answered by the user of the function, not the designer.
Parametrizing over these results in a more complicated, but very general, function. Here's one that I've used for several years:
Then you can write your function by saying:
Depending on whether you want to keep the first or last word starting with, for example, 'h'.
This function is very general, though, so most of the time it's the basis for other functions, like
group_dict
orhistogram
:If you want to use a function instead of subscripting, use operator.itemgetter:
Or as a function:
Finally, if you want more than one word per letter as a possibility, use collections.defaultdict
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:
Output:
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.
If I understand your question correctly, I believe you can accomplish this with a combination of
map
,zip
, and thedict
constructor:And a saner implementation :
Taking hints from other answers I achieved this using map operation. I am not sure if this exactly answers your question.
In Python 3 you can use this dictionary comprehension syntax: