how to input my data into a dictionary from a file?

Viewed 42

I have a file that has following data format:

0
65
88
11
0
11
11

I tried to write below code in order to create a dictionary that the keys are the sequences from 1 to EOF and the values are the data in the file: The code I wrote so far is:

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

The problem is the last line that I cannot figure it out how to do this

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

My desired output should be :

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

Any help would be appreciated

4 Answers

Functional approach:

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

The problem with your current code is that you are attempting to add 1 to a dictionary value that does not exist. hash_1 is defined as an empty dictionary, and your code never actually adds items to it, it simply attempts to increase the value of an item that does not exist. For instance, in the first iteration of the loop, int(data.strip()) evaluates to 0, meaning it's attempting to execute this:

hash_1[0] += 1

hash_1 does not have a value assigned to 0, thus resulting in an exception.

One solution is to use a counter variable starting at 1 and increased iteration, and assign hash_1[<counter>] to the line of data each iteration, like so:

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

i is initially set to 1, and is increased at the end of each iteration of the loop, so the first iteration will assign the key 1 to the first line of data, the second will assign 2 to the next line of data, etc.

file = open('t30.dat','r')
lines = file.readlines()
count = 0 #programmers start the count at 0
for line in lines:
    hash_1[count]=int(line)
    count+=1

I'm not sure why you don't use an array instead but whatever

You can do it in a dictionary comprehension:

with open('t30.dat','r') as f:
    hash_1 = dict(enumerate(int(s.strip()) for s in f.read().split("\n"),1))
Related