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

Winapi c++: DialogBox hangs when breaking a loop -

vb.net - Font adding using PDFsharp -

javascript - jQuery iScroll clickable list elements while retaining scroll? -