python - Writing more compact version of my function -


i have code below in more compact way ( 1 or 2 lines )

foo.txt:

a:1 b:2 c:3 

code:

>>> r = {} >>> in open('foo.txt','r').readlines(): ...     k,v = i.split(':') ...     r[k]=v.strip() 

how about:

in [43]: open("foo.txt") fd:     my_dict=dict(x.strip().split(":") x in fd)    ....:       in [44]: my_dict out[44]: {'a': '1', 'b': '2', 'c': '3'} 

another approach:

in [46]: open("foo.txt") fd:     my_dict={k:v k,v in (x.strip().split(':') x in fd)}    ....:       in [47]: my_dict out[47]: {'a': '1', 'b': '2', 'c': '3'} 

Comments

Popular posts from this blog

c++ - Function signature as a function template parameter -

How to call a javascript function after the page loads with a chrome extension? -

algorithm - What are some ways to combine a number of (potentially incompatible) sorted sub-sets of a total set into a (partial) ordering of the total set? -