简体   繁体   中英

Splitting lines into cols

I have a file like this (end with a blank line)

1 hello hello
4 hello1
...
<emptyline>

I want to make it into dictionary of format {"hello hello":1, "hello1":4} ...key is string, and value is integer

what I do now

dic={}
for line in open(file,'rb'):
    if line.strip:
        idx=line.find(" ")
        cnt=int(line[:idx])
        key=line[idx+1:]
        dic[key]=cnt

Is there a better or shorter way to do this with numpy or other methods?

You could split and use the second parameter of 1 to only split 1 time.

with open('file.txt', 'r') as f:
    d = {}
    for line in f:
        if line.strip():
            value, key = line.split(' ',1)
            d[key] = int(value)

To cut this down into a dict comprehension

with open('file.txt', 'r') as f:
    d = {key:int(value) for value,key in [line.split(' ',1) for line in f if line.split()]}
d = {}
with open('file2.txt') as f:
    for l in f:
        s = l.split(' ')
        d[s[1]] = s[0]  
        print d

Shortest I can get, and should be efficient enough, but kinda cryptic :)

with open('file.txt', 'r') as f:
    rows = map(lambda l: l.strip().partition(' '), f)
    d = { r[2]: int(r[0]) for r in rows if r[2] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM