开发者

How to create a dictionary of integer pairs from a file in python

开发者 https://www.devze.com 2022-12-21 11:27 出处:网络
开发者_JAVA技巧If I have a file of pairs of integer IDs, followed by a value, I\'d like to create this into a dictionary.Each separate term is separated by a newline.I want to make sure these are all
开发者_JAVA技巧

If I have a file of pairs of integer IDs, followed by a value, I'd like to create this into a dictionary. Each separate term is separated by a newline. I want to make sure these are all held as ints. How can I do this?

edit: as requested, a sample.

9 120
10 12
11 4
12 1
13 515
14 32


d={}
f=open("file")
for line in f:
    a,b=map( int, line.split() ) 
    d[a]=b
f.close()
print d

output

$ cat file
9 120
10 12
11 4
12 1
13 515
14 32

$ ./python.py
{9: 120, 10: 12, 11: 4, 12: 1, 13: 515, 14: 32}
0

精彩评论

暂无评论...
验证码 换一张
取 消