ActiveState Powered by ActiveState

Recipe 252176: Dicts from lists


Simple oneliner to built a dictionary from a list

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
"""
The dict built-in function has many ways to build dictionaries but it cannot handle a sequence with alternating key and value pairs.

In python 2.3 it can be easily solved by combining dict, zip and extended slices.
"""

def DictFromList(myList):
    return dict(zip(myList[:-1:2], myList[1::2]))

if __name__ == "__main__":
    print DictFromList(["one", 1, "two", 2, "three", 3])
    # prints: {'three': 3, 'two': 2, 'one': 1}

  

Comments

  1. 1. At 6:11 a.m. on 20 dec 2003, Raymond Hettinger said:

    Generator version. Consider factoring out the pairing logic into a generator. The result is fast, memory friendly, and works with any iterable.

    def pairwise(iterable):
        itnext = iter(iterable).next
        while 1:
            yield itnext(), itnext()
    
    >>> dict(pairwise(["one", 1, "two", 2, "three", 3]))
    {'three': 3, 'two': 2, 'one': 1}
    
  2. 2. At 2:56 p.m. on 20 may 2005, Frank P Mora said:

    Inline quote minimization method.

    I love Python list compressions and prefer to use them as often as
    possible especially as they allow inline generation of lists. I prefer
    them over lambda, map, reduce, filter.
    
    Here’s how it goes.
    
    ls= "one ten two twenty three thirty four forty five fifty".split()
    
    dict( [ (ls[i], ls[i+1]) for I in range(0,len(l),2) ] )
    
    which produces the dictionary
    
    {'four': 'forty', 'three': 'thirty', 'five': 'fifty', 'two': 'twenty', 'one': 'ten'}
    
    If two lists are correlated then you could do the following to
    reduce quoting.
    
    ls1=”one two three four five six seven eight nine ten”
    ls2=”aa1 ab2 ac3   ad4  ae5  af6 ag7   ag8   ah9  ai0”
    
    dict( zip( *[  l.split() for l in (ls1, ls2) ] ) )
    
    This compression produces a nested list which zip interprets as a
    single argument unless you precede the first bracket with an
    asterisk (*) which separates it into multiple (2) argument lists.
    

Sign in to comment