首页 > 解决方案 > 如何将我的数据从文件输入到字典中?

问题描述

我有一个具有以下数据格式的文件:

0
65
88
11
0
11
11

我尝试编写下面的代码以创建一个字典,其中键是从 1 到 EOF 的序列,值是文件中的数据:到目前为止我编写的代码是:

hash_1 ={}
#print(hash_1)
file = open('t30.dat','r')
while True:
    data =file.readline()
    if not data:
        break
    print(int(data.strip()))
    #hash_1[int(data.strip())] += 1

问题是我无法弄清楚如何做到这一点的最后一行

hash_1[int(data.strip())] += 1

我想要的输出应该是:

hash_1= {1:0,2:65,3:88,4:11,5:0,6:11,7:11}

任何帮助,将不胜感激

标签: pythonpython-3.xdictionary

解决方案


功能方法:

with open('t30.dat') as f:
    hash_1 = dict(enumerate(map(int, f), start=1))

推荐阅读