1

I have a list like:

x = ['user=inci', 'password=1234', 'age=12', 'number=33']

I want to convert x to a dict like:

{'user': 'inci', 'password': 1234, 'age': 12, 'number': 33}

what's the quickest way?

Vadim Kotov
  • 7,766
  • 8
  • 46
  • 61
nanci
  • 371
  • 1
  • 4
  • 16

3 Answers3

4

You can do this with a simple one liner:

dict(item.split('=') for item in x)

List comprehensions (or generator expressions) are generally faster than using map with lambda and are normally considered more readable, see here.

Community
  • 1
  • 1
Chris_Rands
  • 35,097
  • 12
  • 75
  • 106
2

Benchmark

dict and map approach (f1)

dict(map(lambda i: i.split('='), x))

Naive approach (f2)

d = dict()
for i in x:
    s = x.split("=")
    d[s[0]] = s[1]
return d

Only dict (f3)

dict(item.split('=') for item in x)

Comparison

def measure(f, x):
    t0 = time()
    f(x)
    return time() - t0

>>> x = ["{}={}".format(i, i) for i in range(1000000)]

>>> measure(f1, x)
0.5690059661865234

>>> measure(f2, x)
0.5518567562103271

>>> measure(f3, x)
0.5470657348632812
Community
  • 1
  • 1
Right leg
  • 14,916
  • 6
  • 44
  • 75
  • when the length of list is very big, the Naive approach is quicker. However , the "dict(item.split('=') for item in x)" method is quicker than Naive approach when the length of list is small. – nanci Jan 10 '17 at 09:31
  • @nanci Actually, that last approach (that you accepted) remains better when the list is huge. – Right leg Jan 10 '17 at 09:35
1

dict(map(lambda i: i.split('='), x))

Lucas Moeskops
  • 5,395
  • 2
  • 25
  • 41