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
  • 8,084
  • 8
  • 48
  • 62
nanci
  • 411
  • 1
  • 5
  • 17

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
  • 38,994
  • 14
  • 83
  • 119
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
  • 16,080
  • 7
  • 48
  • 81
  • 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,445
  • 3
  • 28
  • 42