Search code examples
pythonbinaryfiles

Key-value pairs not functioning of a dictionary when storing the dictionary in a binary file, why?


The purpose of the code is to assign roll no to name, both stored in a dictionary as key-value pairs. The search function should for a given roll no return the corresponding name, but it doesn't, and I have no clue why.

This is the faulty code:

import pickle

f=open('atextfile.dat','wb')
d={}
while True:
    name=input('enter name: ')
    rollno=int(input('enter rollno: '))
    d[rollno]=name
    con=input('Do you want to continue?(y/n): ')
    if con=='n':
        break
print(d)
pickle.dump(d,f)
f.close()

def search():
    f=open('atextfile.dat','rb')
    r=pickle.load(f)
    roll=int(input('what roll no number?: '))
    try:
        n=d[rollno]
        print('name is',n)
    except:
        print('rollno not found :/')
    f.close()

search()

This is the anomalous output I am getting:


Solution

  • change d[rollno] to d[roll] as you used the variable roll for loading the contents of the file

    import pickle
    
    f=open('atextfile.dat','wb')
    d={}
    while True:
        name=input('enter name: ')
        rollno=int(input('enter rollno: '))
        d[rollno]=name
        con=input('Do you want to continue?(y/n): ')
        if con=='n':
            break
    print(d)
    pickle.dump(d,f)
    f.close()
    
    def search():
        f=open('atextfile.dat','rb')
        r=pickle.load(f)
        roll=int(input('what roll no number?: '))
        try:
            n=d[roll] # this was the fault
            print('name is',n)
        except:
            print('rollno not found :/')
        f.close()
    
    search()