KnowledgeBoat Logo

Computer Science

What will be the output of the following code ?

import pickle                             
ID = {1:"Ziva", 2:"53050", 3:"IT", 4:"38", 5:"Dunzo"}                                    
fin = open("Emp.pkl","wb")
pickle.dump(ID, fin)                     
fin.close()                      
fout = open("Emp.pkl",'rb')
ID = pickle.load(fout)
print(ID[5])

Python

Python File Handling

1 Like

Answer

Dunzo

Working

  1. import pickle — Imports the pickle module, which is used for serializing and deserializing Python objects.
  2. ID = {1: "Ziva", 2: "53050", 3: "IT", 4: "38", 5: "Dunzo"} — Defines a dictionary named ID with keys and values.
  3. fin = open("Emp.pkl", "wb") — Opens a file named Emp.pkl in binary write mode ("wb").
  4. pickle.dump(ID, fin) — Serializes the ID dictionary and writes it to the file handle fin using the pickle.dump() function.
  5. fin.close() — Closes the file fin after writing the pickled data.
  6. fout = open("Emp.pkl", 'rb') — Opens the file Emp.pkl again, this time in binary read mode ("rb"), to read the pickled data.
  7. ID = pickle.load(fout) — Deserializes the data from the file fout using the pickle.load() function and assigns it to the variable ID. This effectively restores the original dictionary from the pickled data.
  8. print(ID[5]) — Prints the value associated with key 5 in the restored ID dictionary, which is "Dunzo".

Answered By

3 Likes


Related Questions