I have came across this problem a few times and can\'t seem to figure out a simple solution. Say I have a string
string = \"a=0 b=1 c=3\"
I wan
Nowadays you should probably use a dictionary comprehension, introduced in 2.7:
mydict = {key: int(value) for key, value in (a.split('=') for a in mystring.split())}
The dictionary comprehension is faster and shinier (and, in my opinion, more readable).
from timeit import timeit
setup = """mystring = "a=0 b=1 c=3\""""
code1 = """mydict = dict((n,int(v)) for n,v in (a.split('=') for a in mystring.split()))""" # S.Lott's code
code2 = """mydict = {key: int(value) for key, value in (a.split('=') for a in mystring.split())}"""
print timeit(code1, setup=setup, number=10000) # 0.115524053574
print timeit(code2, setup=setup, number=10000) # 0.105328798294