Home > Software design >  Find key in file
Find key in file

Time:05-23

There is a file that stores the keys in the form of numbers. For example:

81
35
1
56
129

After that, the cycle starts from 0 and up to the given limits. 1, 2, 3, 4, 5, 6....

Help, how to check each variant from the cycle for the presence in the file? If there is such a number in the file on a separate line, then output it.

CodePudding user response:

Hope it helps.

fhandle = open('keys.txt')

# Generate dict of all the keys from the file
key_dict = dict()
for key in fhandle:
    key_dict[int(key)] = key

limit = int(input("Enter search limit: "))
key_found = 0
for i in range(limit):
    search_key = key_dict.get(i, False)
    if search_key:
        print('Key found for: ', i)
        key_found  = 1

print('Total Keys found: ', key_found)
  • Related