![]() |
|
[Tut] How to Save a Dictionary to a File in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Save a Dictionary to a File in Python (/thread-99575.html) |
[Tut] How to Save a Dictionary to a File in Python - xSicKxBot - 06-15-2022 How to Save a Dictionary to a File in Python Rate this post Summary: You can use Python’s Code: pickleCode: JSONProblem: Given a Python dictionary. How will you save the data from the dictionary to a file so that it can be loaded to be used later? You might need the help of persistent storage systems like databases or files to store serialized data structures like arrays, lists, and dictionaries. One of the major reasons behind doing so is databases and files are reusable, i.e., after analyzing the given data, we can store it in the file, and later that data can be read to use in an application. This article will deal with dictionary data that you can store in a file. Example: Consider the following dictionary: Code: d = {'country': 'Germany', 'capital': 'Berlin'}Challenge: How will you store the key-value pairs of the above dictionary in a file? Related Tutorials:
There are numerous ways to store dictionary data in a file using Python. Let’s have a look at some of them: [b]Method 1: Using Pickle[/b]
Approach:
Code: Let’s visualize the above approach with the help of the following code snippet: Code: import pickle
d = {'country': 'Germany', 'capital': 'Berlin'}
file = open("dictionary_data.pkl", "wb")
pickle.dump(d, file)
file.close()
file = open("dictionary_data.pkl", "rb")
output = pickle.load(file)
print(output)
file.close()Output: ![]() Output Console: Code: {'country': 'Germany', 'capital': 'Berlin'}Approach:
Code: Code: import json
d = {'country': 'Germany', 'capital': 'Berlin'}
file = open("dictionary_data.json", "w")
json.dump(d, file)
file.close()
file = open("dictionary_data.json", "r")
output = file.read()
print(output)
file.close()Output: ![]() Output Console: Code: {"country": "Germany", "capital": "Berlin"}Note: The Code: json.dump()[b]Method 3: Using Numpy[/b] Using JSON and Pickle are the best options when it comes to storing a dictionary to a file. But we also have another way of doing so using the Numpy module. Approach: Call the Code: np.save(filename, dictionary)Code: np.load('file.npy', allow_pickle='TRUE').item()Code: Code: import numpy as np
d = {'country': 'Germany', 'capital': 'Berlin'}
np.save('file.npy', d)
read_d = np.load('file.npy', allow_pickle='TRUE').item()
print(read_d)Read Here: NumPy Tutorial – Everything You Need to Know to Get Started Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.) ![]() Method 4: Basic Approach Last but not the least, you can store the dictionary data to a simple text file by simply writing the data to the file using file handling functions. Approach:
Code: d = {'country': 'Germany', 'capital': 'Berlin'}
f = open('file.txt', 'w')
f.write(str(d))
f.close()
f = open('file.txt', 'r')
data = f.read()
print(data)
f.close()Output: ![]() Recommended Reads on File Handling: Conclusion We learned four ways of storing the dictionary data to a file in Python in this article. The most suitable ways of storing the dictionary data in a file are using the JSON or the pickle modules. However, feel free to try out the other ways discussed in this tutorial. I hope this article helped you. Please subscribe and stay tuned for more interesting tutorials and discussions. But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link). If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python! ![]() The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). Link: https://nostarch.com/pythononeliners |