views:

141

answers:

5

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)

+4  A: 

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:

def somefunction(keyFunction, values):
    return dict((keyFunction(v), v) for v in values)

print somefunction(lambda a: a[0], ["hello", "world"])

Output:

{'h': 'hello', 'w': 'world'}

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.

Mark Byers
I'm using this in an open source program, under a BSD style license. I gave you credit, just want to make sure your okay with that?
Jeffrey Aylesworth
I'm OK with it, but am surprised that you would give explicit credit for such a small contribution.
Mark Byers
+3  A: 

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)
sykora
+6  A: 

In Python 3 you can use this dictionary comprehension syntax:

def foo(somelist):
    return {x[0]:x for x in somelist}
mkotechno
+1  A: 

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:

def reduce_list(key, update_value, default_value, l):
    """Reduce a list to a dict.

    key :: list_item -> dict_key
    update_value :: key * existing_value -> updated_value
    default_value :: initial value passed to update_value
    l :: The list 

    default_value comes before l. This is different from functools.reduce, 
    because functools.reduce's order is wrong.
    """
    d = {}
    for k in l:
        j = key(k)
        d[j] = update_value(k, d.get(j, default_value))
    return d

Then you can write your function by saying:

reduce_list(lambda s:s, lambda s,old:s[0], '', ['hello', 'world'])
# OR
reduce_list(lambda s:s, lambda s,old: old or s[0], '', ['hello', 'world'])

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 or histogram:

def group_dict(l):
    return reduce_list(lambda x:x, lambda x,old: [x] + old, [], l)
def histogram(l):
    return reduce_list(lambda x:x, lambda x,total: total + 1, 0, l)
Nathan Sanders
+1  A: 
>>> dict((a[0], a) for a in "hello world".split())
{'h': 'hello', 'w': 'world'}

If you want to use a function instead of subscripting, use operator.itemgetter:

>>> from operator import itemgetter
>>> first = itemgetter(0)
>>> dict((first(x), x) for x in "hello world".split())
{'h': 'hello', 'w': 'world'}

Or as a function:

>>> dpair = lambda x : (first(x), x)
>>> dict(dpair(x) for x in "hello world".split())
{'h': 'hello', 'w': 'world'}

Finally, if you want more than one word per letter as a possibility, use collections.defaultdict

>>> from collections import defaultdict
>>> words = defaultdict(set)
>>> addword = lambda x : words[first(x)].add(x)
>>> for word in "hello house home hum world wry wraught".split():
        addword(word)


>>> print words['h']
set(['house', 'hello', 'hum', 'home'])
Ryan Ginstrom