Welcome, guest | Sign In | My Account | Store | Cart

Simple oneliner to built a dictionary from a list

Python, 12 lines
 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}

  

2 comments

Raymond Hettinger 20 years, 4 months ago  # | flag

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}
Frank P Mora 18 years, 11 months ago  # | flag

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.
Created by Richard Philips on Fri, 28 Nov 2003 (PSF)
Python recipes (4591)
Richard Philips's recipes (6)

Required Modules

  • (none specified)

Other Information and Tasks