python - Efficient way to convert a list to dictionary -


i need in efficient way convert following list dictionary:

l = ['a:1','b:2','c:3','d:4']   

at present, following:

mydict = {} e in l:     k,v = e.split(':')     mydict[k] = v 

however, believe there should more efficient way achieve same. idea ?

use dict() generator expression:

>>> lis=['a:1','b:2','c:3','d:4'] >>> dict(x.split(":") x in lis) {'a': '1', 'c': '3', 'b': '2', 'd': '4'} 

using dict-comprehension ( suggested @paolomoretti):

>>> {k:v k,v in (e.split(':') e in lis)} {'a': '1', 'c': '3', 'b': '2', 'd': '4'} 

timing results 10**6 items:

>>> import * >>> %timeit case1() 1 loops, best of 3: 2.09 s per loop >>> %timeit case2() 1 loops, best of 3: 2.03 s per loop >>> %timeit case3() 1 loops, best of 3: 2.17 s per loop >>> %timeit case4() 1 loops, best of 3: 2.39 s per loop >>> %timeit case5() 1 loops, best of 3: 2.82 s per loop 

so.py:

a = ["{0}:{0}".format(i**2) in xrange(10**6)]  def case1():     dc = {}     in a:         q, w = i.split(':')         dc[q]=w  def case2():     dict(x.split(":") x in a)   def case3():     {k:v k,v in (e.split(':') e in a)}  def case4():     dict([x.split(":") x in a])  def case5():     {x.split(":")[0] : x.split(":")[1] x in a} 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -