Python

NumPy Save Dict

Python is the most widely used user-friendly programming language that can be used for different purposes, such as creating dictionaries into files, reading the same dictionaries, and many more. For doing so, it offers many libraries and packages as well as built-in functions.

This blog will discuss:

What is a Dictionary?

In Python, a dictionary is a built-in unordered data value by enclosing a sequence of entries in curly braces and separated with a comma that can be utilized for storing data values similar to those of a map. Unlike other data types, dictionaries include a key and value pair to make them more efficient.

How to Construct and Store a Dictionary to File in Python?

To save a dictionary to file in Python, initially import the “pickle” module:

import pickle

 

Next, construct a new dictionary using “{}” braces along with the values. Then, use the “print()” function to display the dictionary values:

student = {"Name": "Maria","Country": "United Kingdom", "Capital": "London"}
print('Student Dictionary')
print(student)

 

Now, save the newly created dictionary into your desired file using the “open()” function which opens the file, and the “dump()” function to save dictionary data. In our case, we will save it into the “student_data.pkl” file and print the message:

with open('student_data.pkl', 'wb') as fp:
    pickle.dump(student, fp)
    "print(‘Your dictionary has been saved successfully to file')"

 

According to the following output, we have successfully created and saved the dictionary into the file:

How to Read/Open a Stored Dictionary From a File in Python?

To read a dictionary from a file in Python, use the “open()” method and pass the file name as an argument with the read “rb” operation. Next, use the “pickle” module’s “load()” method and pass it to the variable. Then, call the “print()” statement to view the dictionary values:

with open('student_data.pkl', 'rb') as fp:
    std = pickle.load(fp)
    print('Student Dictionary')
    print(std)

 

Output

That’s it! We have compiled the easiest way to save dictionary values into files in Python.

Conclusion

In Python, a dictionary is an unordered data value that can be utilized for storing data values same to those of a map. To store a dictionary in a file, the “dump()” function can be utilized. Likewise, the “load()” function can be used to read the saved dictionary. In this post, we have illustrated the method for saving dictionary values into files in Python.

About the author

Admin

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.