简体   繁体   中英

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:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM