I would like to have the code below in more compact way ( one or two lines )
foo.txt:
a:1
b:2
c:3
code:
>>> r = {}
>>> for i in open('foo.txt','r').readlines():
... k,v = i.split(':')
... r[k]=v.strip()
I would like to have the code below in more compact way ( one or two lines )
a:1
b:2
c:3
>>> r = {}
>>> for i in open('foo.txt','r').readlines():
... k,v = i.split(':')
... r[k]=v.strip()
怎么样:
In [43]: with open("foo.txt") as fd:
my_dict=dict(x.strip().split(":") for x in fd)
....:
In [44]: my_dict
Out[44]: {'a': '1', 'b': '2', 'c': '3'}
另一种方法:
In [46]: with open("foo.txt") as fd:
my_dict={k:v for k,v in (x.strip().split(':') for x in fd)}
....:
In [47]: my_dict
Out[47]: {'a': '1', 'b': '2', 'c': '3'}
好吧,如果您只关心行数,那就可以了
[r[i.split(':')[0]]=i.split(':')[1] for i in open('foo.txt','r').readlines()]
另一种选择是使用csv
模块:
import csv
with open('input.txt', 'r') as csvfile:
r = {row[0]: row[1] for row in csv.reader(csvfile, delimiter=":")}
这已经非常紧凑了,并且没有从用更少的行数中获得任何好处。
但是,如果您真的必须这样做,那么它就在一行中:
r = dict(i.strip().split(':') for i in open('foo.txt','r').readlines())
我不推荐它,您现有的代码就可以了。