29

I have a list that looks like this:

[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']

And I want to split this list by '=' so that everything on the left side will become keys and on the right, values.

{ 
    'abc':'lalalla',
    'appa':'kdkdkdkd',
    'kkakaka':'oeoeo'
}

5 Answers 5

60
a = [ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']
d = dict(s.split('=') for s in a)
print d


Output:
{'kkakaka': 'oeoeoeo', 'abc': 'lalalla', 'appa': 'kdkdkdkd'}

http://codepad.org/bZ8lGuHE

0
14

In addition, make sure you limit the splits to 1, in case the right-hand side contains an '='.

d = dict(s.split('=',1) for s in a)
0
7
print dict([s.split("=") for s in my_list])

like this

>>> my_list = [ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']
>>> print dict(s.split("=") for s in my_list) #thanks gribbler
{'kkakaka': 'oeoeoeo', 'abc': 'lalalla', 'appa': 'kdkdkdkd'}
2
  • 2
    Unless your python is very old, you can leave the list comprehension out and use a generator expression as Demian does Oct 5, 2012 at 5:33
  • thanks gribbler :) I use 2.6 and always forget I can do that .. mostly because i cant do dict comprehensions Oct 5, 2012 at 5:37
2

You can feed a map object directly to dict. For built-in functions without arguments, map should show similar or better performance. You will see a drop-off in performance when introducing arguments:

from functools import partial

L = ['abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']
L2 = ['abc lalalla', 'appa kdkdkdkd', 'kkakaka oeoeoeo']

n = 100000
L = L*n
L2 = L2*n

%timeit dict(map(partial(str.split, sep='='), L))  # 234 ms per loop
%timeit dict(s.split('=') for s in L)              # 164 ms per loop

%timeit dict(map(str.split, L2))                   # 141 ms per loop
%timeit dict(s.split() for s in L2)                # 144 ms per loop
1

Example by using map function

a = ["abc=lalalla", "appa=kdkdkdkd", "kkakaka=oeoeoeo"]
d = dict(map(lambda s: s.split('='), a))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.