Map list onto dictionary

前端 未结 6 612
-上瘾入骨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:40

    >>> 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'])
    

提交回复
热议问题