Map list onto dictionary

前端 未结 6 603
-上瘾入骨i
-上瘾入骨i 2021-02-02 08:14

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

6条回答
  •  独厮守ぢ
    2021-02-02 08:59

    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)
    

提交回复
热议问题