python - Splitting lines into cols -
i have file (end blank line)
1 hello hello 4 hello1 ... <emptyline>
i want create dictionary of format {"hello hello":1, "hello1":4}
...key string, , value integer
what
dic={} line in open(file,'rb'): if line.strip: idx=line.find(" ") cnt=int(line[:idx]) key=line[idx+1:] dic[key]=cnt
is there improve or shorter way numpy or other methods?
you split
, utilize sec parameter of 1
split 1 time.
with open('file.txt', 'r') f: d = {} line in f: if line.strip(): value, key = line.split(' ',1) d[key] = int(value)
to cutting downwards dict comprehension
with open('file.txt', 'r') f: d = {key:int(value) value,key in [line.split(' ',1) line in f if line.split()]}
python numpy
No comments:
Post a Comment